/* Common CPLAT objects that are required on all pages. Files loaded are:
* digitalspaghetti.password
* BBCWORLDWIDE_CPLAT
* BaseObject
* AjaxOverLayScreenManager
* LoginOverlay
* Comment
* ResetPassword
* loginOverlayHook
*/

/**
 * Title: CPLAT
 * Copyright:	Copyright (c) 2008
 * Company:	BBC Worldwide Ltd
 * Description:	BBCWORLDWIDE_CPLAT namespace
 *
 * @author: NgAW1
 * @version: $Revision: $
 * @date: 10 June 2008 16:51:45
 */

/* @projectDescription jQuery Password Strength Plugin - A jQuery plugin to provide accessibility functions
 * @author Tane Piper (digitalspaghetti@gmail.com)
 * @version 2.0
 * @website: http://digitalspaghetti.me.uk/digitalspaghetti
 * @license MIT License: http://www.opensource.org/licenses/mit-license.php
 * 
 * === Changelog ===
 * Version 2.1 (18/05/2008)
 * Added a jQuery method to add a new rule: jQuery('input[@type=password]').pstrength.addRule(name, method, score, active)
 * Added a jQuery method to change a rule score: jQuery('input[@type=password]').pstrength.changeScore('one_number', 50);
 * Added a jQuery method to change a rules active state: jQuery('input[@type=password]').pstrength.ruleActive('one_number', false);
 * Hide the 'password to short' span if the password is more than the min chars
 * 
 * Version 2.0 (17/05/2008)
 * Completly re-wrote the plugin from scratch.  Plugin now features lamda functions for validation and
 * custom validation rules 
 * Plugin now exists in new digitalspaghetti. namespace to stop any conflits with other plugins.
 * Updated documentation
 * 
 * Version 1.4 (12/02/2008)
 * Added some improvments to i18n stuff from Raffael Luthiger.
 * Version 1.3 (02/01/2008)
 * Changing coding style to more OO
 * Added default messages object for i18n
 * Changed password length score to Math.pow (thanks to Keith Mashinter for this suggestion)
 * Version 1.2 (03/09/2007)
 * Added more options for colors and common words
 * Added common words checked to see if words like 'password' or 'qwerty' are being entered
 * Added minimum characters required for password
 * Re-worked scoring system to give better results
 * Version 1.1 (20/08/2007)
 * Changed code to be more jQuery-like
 * Version 1.0 (20/07/2007)
 * Initial version.
 */
/**
 * Changed password strength calculator. The following rules are now used to calculate strength score:
 * If the password is less than 4 characters then TooShortPassword
 *   * Score += password length * 4
 *   * Score -= repeated characters in the password ( 1 char repetition )
 *   * Score -= repeated characters in the password ( 2 char repetition )
 *   * Score -= repeated characters in the password ( 3 char repetition )
 *   * Score -= repeated characters in the password ( 4 char repetition )
 *   * If the password has 3 numbers then score += 5
 *   * If the password has 2 special characters then score += 5
 *   * If the password has upper and lower character then score += 10
 *   * If the password has numbers and characters then score += 15
 *   * If the password has numbers and special characters then score += 15
 *   * If the password has special characters and characters then score += 15
 *   * If the password is only characters then score -= 10
 *   * If the password is only numbers then score -= 10
 *   * If score > 100 then score = 100
 */

// Create our namespaced object
/*global window */
/*global jQuery */
/*global digitalspaghetti*/
window.digitalspaghetti = window.digitalspaghetti || {};
digitalspaghetti.password = {
    'defaults' : {
        'displayMinChar': true,
        'colors': ["#000", "#ee1c24", "#f7941d", "#f9e400", "#128f35"],
        'scores': [10, 30, 50, 68],
        'verdicts':    ['Weak', 'Ok', 'Good', 'Strong', 'Very Strong']
    },
    'validationRules': function (password) {
        var score = 0;

        if (password.length < 4) {
            return score;
        }
        //password length
        score += password.length * 4;
        score += ( digitalspaghetti.password.checkRepetition(1, password).length - password.length ) * 1;
        score += ( digitalspaghetti.password.checkRepetition(2, password).length - password.length ) * 1;
        score += ( digitalspaghetti.password.checkRepetition(3, password).length - password.length ) * 1;
        score += ( digitalspaghetti.password.checkRepetition(4, password).length - password.length ) * 1;

        //password has 3 numbers
        if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5;

        //password has 2 sybols
        if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5;

        //password has Upper and Lower chars
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10;

        //password has number and chars
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15;
        //
        //password has number and symbol
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 15;

        //password has char and symbol
        if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15;

        //password is just a nubers or chars
        if (password.match(/^\w+$/) || password.match(/^\d+$/))  score -= 10;


        return score;

    },
    'checkRepetition': function (pLen, str) {
        res = "";
        for (i = 0; i < str.length; i++) {
            repeated = true;
            for (j = 0; j < pLen && (j + i + pLen) < str.length; j++)
                repeated = repeated && (str.charAt(j + i) == str.charAt(j + i + pLen));
            if (j < pLen) repeated = false;
            if (repeated) {
                i += pLen - 1;
                repeated = false;
            }
            else {
                res += str.charAt(i);
            }
        }
        return res;
    },
    'attachWidget': function (element) {
        var output = ['<div id="password-strength">'];
        /*if (digitalspaghetti.password.options.displayMinChar && !digitalspaghetti.password.tooShort) {
         output.push('<span class="password-min-char">' + digitalspaghetti.password.options.minCharText.replace('%d', digitalspaghetti.password.options.minChar) + '</span>');
         }*/
        output.push('<p>Password strength: <span></span></p>');
        output.push('<span class="password-strength-bar"></span>');
        output.push('</div>');
        output = output.join('');
        jQuery(element).after(output);
    },
    'init': function (element, options) {
        digitalspaghetti.password.options = jQuery.extend({}, digitalspaghetti.password.defaults, options);
        digitalspaghetti.password.attachWidget(element);
        jQuery(element).keyup(function () {
            digitalspaghetti.password.calculateScore(jQuery(this).val());
        });
    },
    'calculateScore': function (word) {
        digitalspaghetti.password.totalscore = 0;
        digitalspaghetti.password.width = 0;
        var result = digitalspaghetti.password.validationRules(word);
        if (result) {
            digitalspaghetti.password.totalscore += result;
        }

        if (digitalspaghetti.password.totalscore <= digitalspaghetti.password.options.scores[0]) {
            digitalspaghetti.password.strColor = digitalspaghetti.password.options.colors[0];
            digitalspaghetti.password.strText = digitalspaghetti.password.options.verdicts[0];
            digitalspaghetti.password.width = "0";
        } else if (digitalspaghetti.password.totalscore > digitalspaghetti.password.options.scores[0] && digitalspaghetti.password.totalscore <= digitalspaghetti.password.options.scores[1]) {
            digitalspaghetti.password.strColor = digitalspaghetti.password.options.colors[1];
            digitalspaghetti.password.strText = digitalspaghetti.password.options.verdicts[1];
            digitalspaghetti.password.width = "52";
        } else if (digitalspaghetti.password.totalscore > digitalspaghetti.password.options.scores[1] && digitalspaghetti.password.totalscore <= digitalspaghetti.password.options.scores[2]) {
            digitalspaghetti.password.strColor = digitalspaghetti.password.options.colors[2];
            digitalspaghetti.password.strText = digitalspaghetti.password.options.verdicts[2];
            digitalspaghetti.password.width = "104";
        } else if (digitalspaghetti.password.totalscore > digitalspaghetti.password.options.scores[2] && digitalspaghetti.password.totalscore <= digitalspaghetti.password.options.scores[3]) {
            digitalspaghetti.password.strColor = digitalspaghetti.password.options.colors[3];
            digitalspaghetti.password.strText = digitalspaghetti.password.options.verdicts[3];
            digitalspaghetti.password.width = "156";
        } else {
            digitalspaghetti.password.strColor = digitalspaghetti.password.options.colors[4];
            digitalspaghetti.password.strText = digitalspaghetti.password.options.verdicts[4];
            digitalspaghetti.password.width = "208";
        }
        jQuery('.password-strength-bar').stop();

        if (digitalspaghetti.password.options.displayMinChar && !digitalspaghetti.password.tooShort) {
            jQuery('.password-min-char').hide();
        } else {
            jQuery('.password-min-char').show();
        }

        jQuery('.password-strength-bar').animate({opacity: 1}, 'fast', 'linear', function () {
            jQuery(this).css({'display': 'block', 'background-color': digitalspaghetti.password.strColor, 'width': digitalspaghetti.password.width + "px"});
            var className = (digitalspaghetti.password.strText).toLowerCase();
            className = className.split(" ").join("");
            jQuery(this).parent().find("p span").removeClass().addClass(className);
            jQuery(this).parent().find("p span").css("color", digitalspaghetti.password.strColor).text(digitalspaghetti.password.strText);
            jQuery(this).parent().slideDown();
        });
    }
};

jQuery.extend(jQuery.fn, {
    'pstrength': function (options) {
        return this.each(function () {
            digitalspaghetti.password.init(this, options);
        });
    }
});
jQuery.extend(jQuery.fn.pstrength, {
    'changeScore': function (rule, score) {
        digitalspaghetti.password.ruleScores[rule] = score;
        return true;
    },
    'ruleActive': function (rule, active) {
        digitalspaghetti.password.rules[rule] = active;
        return true;
    }
});


 /**
  * This create a namespace BBCWORLDIWDE_CPLAT
  * also contains lots of generic JS functions that can be used for anything
  */
BBCWORLDWIDE_CPLAT = {};

/**
 * This method allow prototypal inheritance where a new object is create from a base object
 * @param base {@link Object}
 * @return Object {@link Object}
*/
BBCWORLDWIDE_CPLAT.newObject = function (o) {
		function F() {}
		F.prototype = o;
		return new F();
};

/**
 * This method creates an object of the request parameters from a given Form object
 * N.B: object is properly encoded by jQuery Ajax method
 * @param oForm {@link Form}
 * @return Object {@link Object}
 */
BBCWORLDWIDE_CPLAT.createRequestParameters = function (oForm) {
	var sRequestParameters = {};
	sRequestParameters.ajaxRequest = true;

	for(i=0; i<oForm.elements.length; i++){
		if((oForm.elements[i].type !== "checkbox") || ((oForm.elements[i].type === "checkbox") && (oForm.elements[i].checked))) {
			if((oForm.elements[i].type !== undefined) && (oForm.elements[i].name.length > 0)) {
				sRequestParameters[oForm.elements[i].name] = oForm.elements[i].value;
			}
		}
	}
	return sRequestParameters;
};


/**
 * This method retrieve or create a Form tag given an input element
 * @param oContainer {@link overLayWindow}
 * @param oInputElement {@link form input element}
 * @return oForm {@link Form}
 */
BBCWORLDWIDE_CPLAT.retrieveFormElement = function (oContainer, oInputElement) {
	var oForm = null;
	if(oInputElement !== undefined) {
		oForm = oInputElement.form;
		if(oForm === null) {
			oContainer.wrap("<form></form>");
			oForm = oInputElement.form;
		}
	}
	return oForm;
};

/**
 * This method retrieve a list of request parameters from query string
 * @param query {@link String}
 * @return params {@link array}
 */
BBCWORLDWIDE_CPLAT.parseQuery = function ( query ) {
	var Params = {};
	   if ( ! query ) {return Params;}// return empty object
	   var Pairs = query.split(/[;&]/);
	   for ( var i = 0; i < Pairs.length; i++ ) {
	      var KeyVal = Pairs[i].split('=');
	      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
	      var key = unescape( KeyVal[0] );
	      var val = unescape( KeyVal[1] );
	      val = val.replace(/\+/g, ' ');
	      Params[key] = val;
	   }
   	return Params;
};

/**
 * This method retrieve the page width and height
 * @return arrayPageSize {@link array}
 */
BBCWORLDWIDE_CPLAT.getPageSize =  function () {
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
};

/**
 * This method detect whether it is a Mac or FireFox
 * @return boolean {@link boolean}
 */
BBCWORLDWIDE_CPLAT.detectMacXFF = function () {
  	var userAgent = navigator.userAgent.toLowerCase();
  	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    		return true;
  	}
};

/**
 * This methid retrieve the window dimension
 * @return object literal {@link object}
 */
BBCWORLDWIDE_CPLAT.getWindowDimension = function () {
	 var x = 0;
	 var y = 0;
	 if (self.innerHeight) {
		 x = self.innerWidth;
		 y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) {
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	
	return {width:x, height:y};
};


/**
 * Title: CPLAT
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description:	BaseObject to provide common hijax and ajax management
 * @author: NgAW1
 * @version: $Revision: $
 * @date: 10 June 2008 16:51:45
 */


/**
 * This define the BBCWORLDWIDE_CPLAT.BaseObject Class, which is a singleton object
 * providing common hijax and ajax management
 * @return this {@link BBCWORLDWIDE_CPLAT.BaseObject}
 */
BBCWORLDWIDE_CPLAT.BaseObject = function() {

    var self = this;
    var clientConfigParams;

    // Getter for clientConfigParams
    this.getClientConfigParams = function() {
        return clientConfigParams;
    };

    // Setter clientConfigParams
    this.setclientConfigParams = function(p_clientConfigParams) {
        clientConfigParams = p_clientConfigParams;
    };

    /**
     * Add Custom email validator to be use in place of JQuery ones that had a bug
     * @return boolean {@link boolean}
     */
    jQuery.validator.addMethod("customEmailCheck", function(value, element) {
        return this.optional(element) || /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})/.test(value);
    }, "Please enter valid email address, yourname@hostname");


    /**
     * Add Custom validator to check whether there are spaces on input element
     * @return boolean {@link boolean}
     */
    jQuery.validator.addMethod("customSpaceCheck", function(value, element) {
        return this.optional(element) || value.indexOf(" ") == -1;
    }, "No space is allowed");


    /**
     * Custom password validator method- checks is password contains minimum number of required numeric characters
     * @return boolean {@link boolean}
     */
    jQuery.validator.addMethod("minNumeric", function(value, element, param) {
        var numericChars = 0;
        numbers = "1234567890";
        for (n = value.length - 1; n >= 0; n--) {
            var cDigit = value.charAt(n);
            if (numbers.indexOf(cDigit) > -1) {
                numericChars = numericChars + 1;
            }
        }
        return numericChars >= param;
    });

    /**
     * Custom password validator method- checks is password contains minimum number of required non-alphaNumeric characters
     * @return boolean {@link boolean}
     */
    jQuery.validator.addMethod("minNonAlphaNumeric", function(value, element, param) {
        var nonAlphaNumChars = 0;
        alphabets = "abcdefghijklmnopqrstuvwxyz";
        numbers = "1234567890";
        for (n = value.length - 1; n >= 0; n--) {
            var cDigit = value.charAt(n);
            if (numbers.indexOf(cDigit) < 0 && alphabets.indexOf(cDigit) < 0) {
                nonAlphaNumChars = nonAlphaNumChars + 1;
            }
        }
        return nonAlphaNumChars >= param;
    });


    /**
     * Template method to support hijax of form submit, it calls addValidation and addScreenHandler that can be overridden by inheriting object
     */
    this.hijax = function() {
        self.getClientConfigParams().cplatContainer.find("form").each(function() {
            self.addValidation(this);
            self.addScreenHandler(this);
        });
    };

    /**
     * Default no validation required, need to override to provide screen specific validation
     */
    this.addValidation = function (oForm) {
    };

    /**
     * Default no validation required, need to override to provide screen specific validation
     */
    this.ajaxSaveCallback = function (oForm) {
    };

    /**
     * Override this if you want to add specific processing steps for Screen Handler, this just validate inputs within a form and call form submit
     */
    this.addScreenHandler = function(oForm) {
        var oSubmitButton = $(oForm).find("input[type='submit']");
        if (oSubmitButton.get(0) != null) {
            oSubmitButton.click(function() {
                if ($(oForm).valid()) {
                    oForm.submit();
                }
                return false;
            });
        }
    };

    /**
     * Retrieve Validation Messages form with xhtml fragment
     * @return messages {@link messages}
     */
    this.getValidationMessages = function () {
        if (typeof(BBCWORLDWIDE_CPLAT_getValidationMessages) === 'function') {
            return BBCWORLDWIDE_CPLAT_getValidationMessages();
        } else {
            return {};
        }
    };

    /**
     * Retrieve Validation Rules from with xhtml fragment
     * @return messages {@link messages}
     */
    this.getValidationRules = function () {
        if (typeof(BBCWORLDWIDE_CPLAT_getValidationRules) === 'function') {
            return BBCWORLDWIDE_CPLAT_getValidationRules();
        } else {
            return {};
        }
    };


    /**
     *  Private Method to Clean Ajax Status Message
     */
    var showHide = function() {
        var showDetails = $(this).parent().parent().next('.cplat-editable');
        if (showDetails.is(':visible')) {
            showDetails.slideUp('slow');			
        } else {
            showDetails.slideDown('slow');
			showDetails.find('p.cplatAjaxSuccessMessage').remove();
			showDetails.prev().slideUp('slow');			
        }
        return false;
    };

    /**
     *  Private Method to Clean Ajax Status Message
     */
    var hide = function() {
        var hideDetails = $(this).parent().parent('.cplat-editable');
        if (hideDetails.is(':visible')) {
            hideDetails.slideUp('slow');
			hideDetails.prev().slideDown('slow');
        }
        return false;
    };


    /**
     *  Add event handler to toggle Change / hide link to show hide next sibling so that submit button can be clicked
     *   - to see in action look at editPersonDetails page on test client
     */
    this.ajaxToggleChangeLink = function(oForm, submitAction, submitMethod, redirectPath) {
        // Show the change link but hide the inputs - default to support non javascripts, change link is hidden and input is displayed
        $(oForm).find('div.changeClick').show();
        $(oForm).find("input[type='button']").show();
        $(oForm).find('div.cplat-editable').hide();
		$(oForm).find("div.buttons").show();
		$(oForm).find("#cplat-details-submit").hide();

        // Show the input when change link is clicked
        $(oForm).find("a.bChange").click(showHide);
        $(oForm).find("input.cplat-cancel-button").click(hide);

        // When the button is clicked, make call to save via AJAX
        $(oForm).find("input.cplat-save-button").click(function() {
            var requestParameters = "";

            // Allow subclass to retrieve application specific request parameter based on specific logic, SEE EditPersonalDetails.js where this is being used.
            if (typeof(self.retrieveApplicationSpecificRequestParameter) === 'function') {
                requestParameters = self.retrieveApplicationSpecificRequestParameter($(this).parent().parent());
            } else {
                // Default just read request parameters from supplied container div
                requestParameters = self.retrieveRequestParametersFromContainer($(this).parent().parent());
            }


            //Appending InitialHashCode - as it will not always be present in the container being sent to retreiveRequestParams (eg in EditPersonalDetails form)
            if ($(oForm).find("input[name='cplat-initialHashCode']").get(0) !== undefined) {
                requestParameters = requestParameters + "&cplat-initialHashCode=" + $(oForm).find("input[name='cplat-initialHashCode']").val();
            }

            // Make call to ajaxSave to persist the change
            self.ajaxSave($(this).parent().parent(), submitAction, submitMethod, requestParameters, redirectPath);
        });
    };

    /**
     *  Wrap standard JQuery Ajax to provide customised CPLAT saving and error handling capability
     */
    this.ajaxSave = function(divContainer, submitAction, submitMethod, requestParameters, redirectPath) {
        clearAjaxStatusMessages($(divContainer));
        var sSavingMessage = "<p class='cplatAjaxInfoMessage'>Saving, please wait ...</p>";
		$(divContainer).find("div.buttons").after(sSavingMessage);
        $.ajax({
            type: submitMethod,
            url: submitAction,
            data: requestParameters,
            cache: false,
            success: function(data) {
                //if email redirect immediately on success
                if (($(divContainer).find("#cplat_email").get(0) !== undefined)){
                       window.location = redirectPath;
                    }

                clearAjaxStatusMessages($(divContainer));
                var sSuccessMessage = "<p class='cplatAjaxSuccessMessage'>Successfully saved</p>";
                $(divContainer).find("div.buttons").after(sSuccessMessage);
                var oFirstInputValue = $(divContainer).find("select:first").get(0);
                var replaceText = "";
                // It is a select box
                if ((oFirstInputValue !== undefined)) {
                    replaceText = oFirstInputValue.options[oFirstInputValue.selectedIndex].text;
                    if (((replaceText == 'other') || (replaceText == 'Other')) && $(divContainer).find(":text").get(0) !== undefined) {
                        replaceText = "";
                    }
                    $(divContainer).find(":text").each(function() {
                        replaceText += " " + $(this).val();
                    });
                } else {
                    $(divContainer).find(":text").each(function() {
                        replaceText += $(this).val() + " ";
                    });
                }

                $(divContainer).prev().find("span.changeValue").html(replaceText);
				$(divContainer).animate({opacity:1.0}, 1000);
                $(divContainer).prev().find("a.bChange").trigger("click");
				$(divContainer).prev().slideDown('slow');

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                var resultXML = XMLHttpRequest.responseXML;
                clearAjaxStatusMessages($(divContainer));
                var nodes = $(resultXML).find("error invalidFields invalidField").each(function() {
                    var originalFieldName = $(this).attr("originalFieldName");
                    var errorMessageHTML = "<p class='error'>" + $(this).find("errorMessage").text()  + "</p>";
                    $(divContainer).find("input[name='" + originalFieldName + "']").after(errorMessageHTML);
                });
                //Cleaning conflict error message in case of other errors. Should be displayed only in case of 409
                $("#cplat-xhtml-container").find("div[name='cplat-dynamicConflictMsg']").html("");
                //Adding error message for Conflict error
                if (XMLHttpRequest.status === 409) {
                    var conflictErrorMessage = "Sorry, your changes couldn't be saved. Please try again later.";
                    $("#cplat-xhtml-container").find("div[name='cplat-dynamicConflictMsg']").html(conflictErrorMessage);

                }
            },
            complete: function(XMLHttpRequest, textStatus) {

                if (XMLHttpRequest.getResponseHeader("cplat_initialHashCode") !== null) {
                    $("#cplat-xhtml-container").find("input[name='cplat_initialHashCode']").val(XMLHttpRequest.getResponseHeader("cplat_initialHashCode"));
                }
            }


        });
    };


    /**
     *  Wrapper to the standard JQuery AJAX, providing CPLAT specific error handling
     */
    this.ajaxSubmit = function(submitButton,
                               submitAction,
                               submitMethod,
                               requestParameters,
                               successCallBackFunc,
                               errorCallBackFunc) {
        clearAjaxStatusMessages($(submitButton).form);
        $.ajax({
            type: submitMethod,
            url: submitAction,
            data: requestParameters,
            cache: false,
            success: function(data) {
                if (typeof(successCallBackFunc) === 'function') {
                    successCallBackFunc(data);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                var resultXML = XMLHttpRequest.responseXML;
                clearAjaxStatusMessages($(submitButton).form);
                var nodes = $(resultXML).find("error invalidFields invalidField").each(function() {
                    var originalFieldName = $(this).attr("originalFieldName");
                    var errorMessageHTML = "<p class='error'>" + $(this).find("errorMessage").text() + "</p>";
                    $($(submitButton).form).find("input[name='" + originalFieldName + "']").after(errorMessageHTML);
                });

                if (typeof(errorCallBackFunc) === 'function') {
                    errorCallBackFunc(XMLHttpRequest, textStatus, errorThrown);
                }
            }
        });
    };

    /**
     *  Wrapper to the standard JQuery AJAX call to retrieve a screen
     */
    this.ajaxGet = function(url,
                            method,
                            requestParameters,
                            successCallBackFunc,
                            errorCallBackFunc,
                            applicationSuccessCallBackFunc,
                            xhrCompleteCallBackFunc) {
        return $.ajax({
            type: method,
            url: url,
            data: requestParameters,
            cache: false,
            success: function(data) {
                if (typeof(successCallBackFunc) === 'function') {
                    successCallBackFunc(data);
                }

                if (typeof(applicationSuccessCallBackFunc) === 'function') {
                    applicationSuccessCallBackFunc(data);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (typeof(errorCallBackFunc) === 'function') {
                    errorCallBackFunc(XMLHttpRequest, textStatus, errorThrown);
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                if (typeof(xhrCompleteCallBackFunc) === 'function') {
                    xhrCompleteCallBackFunc(XMLHttpRequest, textStatus);
                }
            }
        });

    };

    /**
     *  Support retrieve of request Parameters from within a DOM container
     * @return string {@link string}
     */
    this.retrieveRequestParametersFromContainer = function(oContainer) {
        var sRequestParameters = "ajaxRequest=true";
        oContainer.find("input").each(function () {
            if ((($(this).attr("type") !== "checkbox") && ($(this).attr("type") !== "radio")) ||
                (($(this).attr("type") === "checkbox") && ($(this).get(0).checked)) ||
                (($(this).attr("type") === "radio") && ($(this).get(0).checked))) {
                if ($(this).attr("type") !== undefined) {
                    sRequestParameters = sRequestParameters + "&" + $(this).attr("name") + "=" + $(this).val();
                }
            }
        });

        oContainer.find("select").each(function () {
            if (sRequestParameters.length == 0) {
                sRequestParameters = sRequestParameters + $(this).attr("name") + "=" + $(this).val();
            } else {
                sRequestParameters = sRequestParameters + "&" + $(this).attr("name") + "=" + $(this).val();
            }
        });
        return sRequestParameters;
    };

    /**
     *  Wrapper to the JQuery Password Strength plugin
     */
    this.addPasswordStrength = function(p_oInput) {

        if (p_oInput.get(0) != null) {
            var oForm = p_oInput.get(0).form;
            if (oForm != null) {
                var oPasswordStrengthDiv = $(oForm).find("div[id='password-strength']");
                if (oPasswordStrengthDiv.get(0) === undefined) {
                    p_oInput.pstrength();
                }
            }
        }
    };


    /**
     * Make AJAX call to validate field
     */
    this.addRemoteValidation = function(url, method, p_oInput) {
        $(p_oInput).blur(function() {
            var fieldname = $(p_oInput).attr("name");
            var validationUrl = url + fieldname  + "=" + $(p_oInput).attr("value");
            // cplatRequestDateTime is passed to prevent caching of value
            // NOTE - the server-side call must return JSON
            $.getJSON(validationUrl,
            {cplatRequestTime: (new Date()).getTime()},
                    function(data) {
                        var field = data[fieldname];
                        $(p_oInput).nextAll("p.ajaxError").remove();
                        if ((field !== undefined) && (field.validate === true)) {
                            var errorMessageHTML = "<p class='error ajaxError'>" + field.errorMessage + "</p>";
                            $(p_oInput).after(errorMessageHTML);
                        } 
                    });
        });
    };


    /**
     *  Private Method to Clean Ajax Status Message
     */
    var clearAjaxStatusMessages = function(p_oContainer) {
        $(p_oContainer).find(".cplatAjaxInfoMessage").remove();
        $(p_oContainer).find(".cplatAjaxSuccessMessage").remove();
        $(p_oContainer).find("p.error").remove();
    };

    return this;
}();

/**
 * Title: CPLAT
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description:	AjaxOverLayScreenManager to manage display of screen on popup overlay window
 * @author: NgAW1
 * @version: $Revision: $
 * @date: 10 June 2008 16:51:45
 */
 

/**
 * This define the AjaxOverLayScreenManager Class, which is a singleton object
 * providing Ajax OverLay Screen Management functionalities
 * @param base {@link BBCWORLDWIDE_CPLAT.BaseObject}
 * @return this {@link BBCWORLDWIDE_CPLAT.AjaxOverLayScreenManager}
 */
BBCWORLDWIDE_CPLAT.AjaxOverLayScreenManager = function(base) {
	var arrayScreens = new Array(); // Array of Screens definitions
	var overLayHeight  = 350; // Overlay height, default 350  - can be supplied by hook in clientConfigParams using userDefinedOverLayDimension.height
	var overLayWidth   = 600; // Overlay width, default 600 - can be supplied by hook in clientConfigParams using userDefinedOverLayDimension.width
	var currentScreen = 0; // current screen definition being displayed
	var passionSiteCallBackFunc; // call back function supplied by passion Site 
	var passionSiteErrorCallBackFunc; // error call back function supplied by passion site
	var passionSiteOverlayCloseCallBackFunc; // call bacj function when overlay is close
	var imgLoader = new Image();

	// Getter for passionSiteCallBackFunc
	base.getPassionSiteCallBackFunc = function() {
		return passionSiteCallBackFunc;
	};
    
	/**
	 * This method setup the onclick handler for opening the overlay screen to load xhtml fragment via AJAX call
	 * @param: p_oClickedLink {@link archor tag}
	 */ 
	
	base.handleLinkClick  = function(p_oClickedLink) {
		 
		// Don't show in overlay if screen is too small
		if (isScreenTooSmallForOverlay()) {
			window.location = $(p_oClickedLink).attr("href");
			return;
		}
		
		// If user hasn't defined screen flows then we just use href and title from the clicked links
		// note: now all interaction goes through client aplpication, unlikely we need to use screen flows
		// so most likely the href and title will be used to define the screen that will be rendered in overlay
		if (base.getClientConfigParams().userDefinedScreensFlow != null) {
			 arrayScreens = base.getClientConfigParams().userDefinedScreensFlow;
		} else {
			arrayScreens[0] = {
				retrieveURL:$(p_oClickedLink).attr("href"),
				screenTitle:$(p_oClickedLink).attr("title")
			};
		}
		
		// If user defined screen height and width then use it, otherwise use default
		if (base.getClientConfigParams().userDefinedOverLayDimension != null) {
			overLayHeight  = base.getClientConfigParams().userDefinedOverLayDimension.height;
			overLayWidth   = base.getClientConfigParams().userDefinedOverLayDimension.width;
		} 
		
		// Passion site callback
		if ((base.getClientConfigParams() != null) && (base.getClientConfigParams().passionSiteCallBack !=null)) {
			passionSiteCallBackFunc             = base.getClientConfigParams().passionSiteCallBack.successCallBack;
			passionSiteErrorCallBackFunc        = base.getClientConfigParams().passionSiteCallBack.errorCallBack;
			passionSiteOverlayCloseCallBackFunc = base.getClientConfigParams().passionSiteCallBack.overlayCloseCallBack;
		}
		currentScreen = 0;

		// we should have at least 1
		if(arrayScreens.length > 0) {
			for(i=0; i<arrayScreens.length; i++) {
				if(arrayScreens[i].applicationSuccessCallBackFunc === undefined) {
					arrayScreens[i].applicationSuccessCallBackFunc = function() {};
				}
			}
			showScreen(getCurrentScreen());
		}
	};
	
	/**
 	 * This method is call when successfully retrieved an xhtml fragment via AJAX call
 	 * @param: overLayWindow {@link  dom}
 	 * @param: fCloseOverlayFunc {@link  Function}
 	 */
	base.overLayWindowAjaxSuccessHook = function (overLayWindow, fCloseOverlayFunc) {
		// Add an onclick handler when a submit button is clicked
		overLayWindow.find("input[type='submit']").click(function() {
			if(!$(this.form).valid()) {
				return;
			}
		
			if(typeof(base.cplatPreProcessHandler) === "function") {
				base.cplatPreProcessHandler(fCloseOverlayFunc);
			}
			$.ajax({
				url: $(this.form).attr("action"),
				type: $(this.form).attr("method"),
				data: BBCWORLDWIDE_CPLAT.createRequestParameters(this.form),
				// If success then either retrieve next screen or call passionSiteCallBackFunction
				success: function(xhtml){
					jQuery.unblockUI();
					// If it is just xhtml fragment then display it
					if( (typeof(xhtml) === 'string') && (xhtml.length > 0)  )  {
						injectXHTMLFragment(xhtml);
					} else {
						currentScreen++;
						if(arrayScreens.length > currentScreen) {
							// if another screen is defined in hook code then get the screen then show it
							var url = getCurrentScreen().retrieveURL;
							showScreen(getCurrentScreen());
						} else {
							// otherwise if a postProcessHandler has been defined then call it
							if(typeof(base.cplatSuccessfulPostProcessHandler) === "function") {
								base.cplatSuccessfulPostProcessHandler(fCloseOverlayFunc);
							} 
							currentScreen = 0;
							if(typeof(passionSiteCallBackFunc) === "function") {
								// if a final callback function has been defined then call it
								passionSiteCallBackFunc.call(overLayWindow);
							}
						}
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					jQuery.unblockUI();
					// If it is just xhtml fragment then display it
					if( (typeof(xhtml) === 'string') && (xhtml.length > 0)  )  {
						injectXHTMLFragment(xhtml);
					} else {
						if(typeof(passionSiteErrorCallBackFunc) === "function") {
							passionSiteErrorCallBackFunc.call(overLayWindow);
						}
					}
				}
			});
			
			return false;
		});
	};
	
	// Override this method if you want to do something different than default
	// this default impl shows a dodgy rotating gif..
	base.cplatPreProcessHandler = function (fCloseOverlayFunc) {
		if($("#cplatPreProcessMessage").get(0) !== undefined) {
			var cplatPreProcessMessage = $("#cplatPreProcessMessage");
			jQuery.blockUI({ message: cplatPreProcessMessage});
		} else {
			jQuery.blockUI({ message: "<img src='"+imgLoader.src+"' />"});
		}
	};
	
	// Override this method if you want to do something different than default
	base.cplatSuccessfulPostProcessHandler = function (fCloseOverlayFunc) {
		if($("#cplatSuccessfulPostProcessMessage").get(0) !== undefined) {
			jQuery.blockUI({ message: $("#cplatSuccessfulPostProcessMessage")});
			$('.cplatSuccessOK').click(function() { 
				jQuery.unblockUI(); 
				return false;
			}); 
		}
		fCloseOverlayFunc.call();
	};
	
	// Override this method if you want to do something different than default
	base.cplatExceptionProcessHandler = function (fCloseOverlayFunc) {
		if($("#cplatExceptionProcessMessage").get(0) !== undefined) {
			jQuery.blockUI({ message: $("#cplatExceptionProcessMessage")});
			$('#ok').click(function() { 
				jQuery.unblockUI(); 
				return false;
			}); 
		}
		fCloseOverlayFunc.call();
	};
	
	// Shows the next screen
	base.showNextScreen =  function () {
		var screen = getNextScreen();
		if (screen!==null){
			showScreen(screen);
		}
	};

	// Returns current Screen
	var getCurrentScreen = function() {
		if(arrayScreens.length > 0) {
			return arrayScreens[currentScreen];
		}
	};

	// Returns next Screen
	var getNextScreen = function() {
		if(arrayScreens.length >= currentScreen+1 ) {
			return arrayScreens[currentScreen+1];
		}
		return null;
	};
    

	/**
	 * This method do the main work of creating/displaying the overlay, make AJAX call, inject xhtml into DOM and 
	 * make calls to the call back function
	 * @param: caption {@link  String}
	 * @param: url {@link  String}
	 */
	var showScreen = function(screen) {
		try {
			var caption = screen.screenTitle;
			var url = screen.retrieveURL;
			var applicationSuccessCallBackFunc = screen.applicationSuccessCallBackFunc;

			// Create the Div that display the OverLay
			if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
				$("body","html").css({height: "100%", width: "100%"});
				$("html").css("overflow","hidden");

				//iframe to hide select elements in ie6
				if (document.getElementById("cplat-HideSelect") === null) {
					$("body").append("<iframe id='cplat-HideSelect'></iframe><div id='cplat-overlay'></div><div id='cplat-window'></div>");
					$("#cplat-overlay").click(removeScreen);
				}
			} else {
				if (document.getElementById("cplat-overlay") === null){
					$("body").append("<div id='cplat-overlay'></div><div id='cplat-window'></div>");
					$("#cplat-overlay").click(removeScreen);
				}
			}
			
			// Set OverLay Background		
			if (BBCWORLDWIDE_CPLAT.detectMacXFF()){
				$("#cplat-overlay").addClass("cplat-overlayMacFFBGHack"); //use png overlay so hide flash
			} else {
				$("#cplat-overlay").addClass("cplat-overlayBG");	//use background and opacity
			}
					
			if (caption===null) {
				caption="";
			}


			// Display an image during load		
			if( base.getClientConfigParams().overlayImgLoader != null) {
				imgLoader.src = base.getClientConfigParams().overlayImgLoader;
			}
			$("body").append("<div id='cplat-load'><img src='"+imgLoader.src+"' /></div>");
			$('#cplat-load').show();
			
			// Set Width and Height of OverLay Window
			CPLAT_WIDTH  = (overLayWidth*1) || 630;
			CPLAT_HEIGHT = ( overLayHeight*1) || 440; 			
			
			// Load OverLay with data returns from AJAX Calls
			if ($("#cplat-window").css("display") != "block") {
				$("#cplat-overlay").unbind();
				$("#cplat-window").append("<div id='cplat-title'><div id='cplat-ajaxWindowTitle'>"+caption+"</div><div id='cplat-closeAjaxWindow'><a href='#' id='cplat-closeWindowButton'>close</a></div></div><div id='cplat-ajaxContent' class='cplat-modal'></div>");
			} else {//this means the window is already up, we are just loading new content via ajax
					$("#cplat-ajaxContent")[0].scrollTop = 0;
					$("#cplat-ajaxWindowTitle").html(caption);
			}

			// Add Handler to Close Button to remove Screen
			$("#cplat-closeWindowButton").click(removeScreen);

			base.ajaxGet(url, "GET", "ajaxRequest=true", injectXHTMLFragment, passionSiteErrorCallBackFunc, applicationSuccessCallBackFunc, null);
			
		} catch(e) {
			console.log(e);
		}
	};
	
	// Private Method to inject content
	var injectXHTMLFragment = function (xhtml) {
		var oTBAjaxContent = $("#cplat-ajaxContent");
		var oTBLoad = $("#cplat-load");
		var oTBWindow = $("#cplat-window");
		oTBAjaxContent.children().remove();
		oTBAjaxContent.append(xhtml);
		$("#cplat-window").css({marginLeft: '-' + parseInt((CPLAT_WIDTH / 2),10) + 'px', width: CPLAT_WIDTH + 'px', height: CPLAT_HEIGHT + 'px'});
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
			$("#cplat-window").css({marginTop: '-' + parseInt((CPLAT_HEIGHT / 2),10) + 'px'});
		}
		
		oTBLoad.remove();
		oTBWindow.css({display:"block"});
		
		if(typeof(base.overLayWindowAjaxSuccessHook) === 'function') {
			base.overLayWindowAjaxSuccessHook(oTBWindow, removeScreen);
		}
	};
	
	/**
	 * closes the overlay
	 * 
	 * exposes the functionality to the interface
	 */
	base.closeOverlay = function() {
		removeScreen();
	};
	
	// Private Method to remove
	var removeScreen = function () {
		$("#cplat-imageOff").unbind("click");
		$("#cplat-closeWindowButton").unbind("click");
		$("#cplat-window").fadeOut("fast",function(){$('#cplat-window,#cplat-overlay,#cplat-HideSelect').trigger("unload").unbind().remove();});
		$("#cplat-load").remove();
		if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
			$("body","html").css({height: "auto", width: "auto"});
			$("html").css("overflow","");
		}
		document.onkeydown = "";
		document.onkeyup = "";
		
		if (typeof(passionSiteOverlayCloseCallBackFunc) === 'function') {
			passionSiteOverlayCloseCallBackFunc.call();
		}
		
		// Set currentScreen to 0
		currentScreen = 0;
		
		return false;
	};
	
	// Determine whether the window is too small to show in an overlay
	// if window is too small for an overlay then the normal page is displayed (non-overlay)
	var isScreenTooSmallForOverlay = function () {
		var dimensionAllowance = 100;
		var dimension = BBCWORLDWIDE_CPLAT.getWindowDimension();
		return (( dimension.width < (overLayWidth + dimensionAllowance)) || (dimension.height < (overLayHeight + dimensionAllowance)));
	};
	
	return base;
}(BBCWORLDWIDE_CPLAT.BaseObject);

/**
 * Title: BBCWORLDWIDE_CPLAT.LoginOverlay
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description: Login Screen to handle CPLAT login overlay panel
 * @author: NgAW1
 * @version: $Revision: $
 * @date: 10 June 2008 16:51:45
 */


/**
 * This define the BBCWORLDWIDE_CPLAT.LoginOverlay Class, which override the singleton object 
 * from BBCWORLDWIDE_CPLAT.AjaxOverLayScreenManager.
 * @param base {@link BBCWORLDWIDE_CPLAT.AjaxOverLayScreenManager}
 * @return  BBCWORLDWIDE_CPLAT.Registration {@link  BBCWORLDWIDE_CPLAT.Registration}
 */
BBCWORLDWIDE_CPLAT.LoginOverlay = function(base, p_oParams) {

    base.setclientConfigParams(p_oParams);

    // Override the parentThickBoxAjaxSuccess by hooking to screen specific validation
    var parentOverLayWindowBoxAjaxSuccessHook = base.overLayWindowAjaxSuccessHook;
    base.overLayWindowAjaxSuccessHook = function (overLayWindow, fCloseOverlayFunc) {
        var oSubmitButton = overLayWindow.find("input[type='submit']");
        var oForm = BBCWORLDWIDE_CPLAT.retrieveFormElement(overLayWindow, oSubmitButton.get(0));
				
				$('<a href="#" class="cplat-closeLoginOverlay">Close</a>').insertAfter(oSubmitButton).click(base.closeOverlay);
				
				$('#cplat-overlay').click(base.closeOverlay);
				
				$('body').keypress(function(e) {
					if ( e.keyCode === 27 ) {
						base.closeOverlay();
					}
				});
				
				
        // Hijax forgot-password link, and replace with new forgot pwd overlay when clicked
        // $(overLayWindow).find("a[title='forgot-password']").click(function() {
        //     BBCWORLDWIDE_CPLAT.ForgotPasswordOverlay(base, base.getClientConfigParams()).handleLinkClick(this);
        //     return false;
        // });

        // Hijax register link, and replace with new registration overlay when clicked
        // $(overLayWindow).find("a[title='register']").click(function() {
        //     BBCWORLDWIDE_CPLAT.RegistrationOverlay(base, base.getClientConfigParams()).handleLinkClick(this);
        //     return false;
        // });


        // Intercept update-email link
        // $(overLayWindow).find("a[title='change-email']").click(function() {
        //     BBCWORLDWIDE_CPLAT.LoginOverlay(base, base.getClientConfigParams()).handleLinkClick(this);
        //     return false;
        // });

        // Intercept resend-email link
        // $(overLayWindow).find("a[title='resend-email']").click(function() {
        //     BBCWORLDWIDE_CPLAT.LoginOverlay(base, base.getClientConfigParams()).handleLinkClick(this);
        //     return false;
        // });

        // Delegate back to parent Thick Box to complete SuccessHook
        //parentOverLayWindowBoxAjaxSuccessHook(overLayWindow, fCloseOverlayFunc);
    };

    return base;
};

/**
 * Title: BBCWORLDWIDE_CPLAT.SaveComment
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description: Handles Javascript submit for Save Ugc flow
 * @author: SaxenNW1
 * @version: $Revision: $
 * @date: 21 July 2008 16:05:29
 */


/**
 * This define the BBCWORLDWIDE_CPLAT.Ugc Class - overrrides the singleton common BaseObject
 * @param base {@link BBCWORLDWIDE_CPLAT.BaseObject}
 * @return  BBCWORLDWIDE_CPLAT.Ugc {@link  BBCWORLDWIDE_CPLAT.Ugc}
 */
BBCWORLDWIDE_CPLAT.Comment = function(base, p_oParams) {

    /**
     * p_oParams - comment configuration params :
     *    cplatContainer:   the container DIV id
     *    truncateLength:   the length comment text will be truncated too
     *    voteUrl:          the client application URL for posting a vote
     */
    base.setclientConfigParams(p_oParams);

    // when doc has loaded add click handlers to voting links and add trunctae plugin to commentText
    $(document).ready(function() {
        // add truncate functionality to comment text
        $(".cplatTruncatedMoreLess").truncate( base.getClientConfigParams().truncateLength, {
            chars: /\s/,
            trail: [ " ( <a href='#' class='truncate_show'>more</a> . . . )", " ( . . . <a href='#' class='truncate_hide'>less</a> )" ]
        });
        // add click event handlers onto the voting buttons/text
        $("a.voteYes").click(voteYes);
        $("a.voteNo").click(voteNo);
        //$("#cplat-moderateCommentSubmit").click(moderate);
         expandModerationBox();




    });

    // add the form validation messages + rules
    base.addValidation = function (oForm) {
        $(oForm).validate({rules:base.getValidationRules(),messages:base.getValidationMessages()});
    };


    /**
     * Expands the moderation box to show the moderation form
     *
     */
    function expandModerationBox() {
        $('p.cplat-commentModerate, input.cplat-cancel-button').click(function() {

            var answer = $(this).next('div.cplat-commentModeration');
            if (answer.is(':visible')) {
                answer.slideUp('slow');
            } else {

                $('div.cplat-commentModeration:visible').slideUp('slow');
                answer.slideDown('slow');
            }

            return false;
        });

    }
    

    /**
     * Event handler for the onclick event of the Vote YES button/link
     */
    function voteYes() {
        return vote(this, true);
    };

    /**
     * Event handler for the onclick event of the Vote NO button/link
     */
    function voteNo() {
        return vote(this, false);
    };

    /**
     * Do and AJAX POST of the vote to CPLAT (via the client)
     * @param useful - boolean true if voting useful
     */
    function vote(element, useful){
        var clickedurl = $(element).attr("href");
        var commentIdParam = clickedurl.match(/cplat_commentId=.+/)[0];
        var commentId = commentIdParam.substring(commentIdParam.indexOf("=")+1);
        var url = p_oParams.voteUrl + "?ajaxRequestURL=/comment-vote/" + commentId + "&useful=" + (useful ? "true" : "false");
        eval("var voteSuccessCallbackProxy = function(data) {voteSuccessCallback('" + commentId + "', data);};");
        eval("var voteErrorCallbackProxy = function(data) {voteErrorCallback('" + commentId + "', data);};");
        base.ajaxGet(url, "POST", "ajaxRequest=true", voteSuccessCallbackProxy, voteErrorCallbackProxy, null, votingCompleteCallback);
        return false;
    };

    /**
     * removes the error status message
     */
    function removeStatusMessage(commentId){
        $("#cplat-commentVoting"+commentId).find(".commSaveStatus").remove();
    };

    /**
     * Success callback from Ajax Vote POST
     */
    var voteSuccessCallback = function(commentId, data){
        $("#cplat-commentVoting"+commentId).html(data);
    };

    /**
     * Error callback from Ajax Vote POST
     */
    var voteErrorCallback = function(commentId, xhr){
        removeStatusMessage(commentId);
        $("#cplat-isThisUseful"+commentId).after("<label class='commSaveStatus'>There was an error and your vote was not registered</label>");
        setTimeout(new function(){removeStatusMessage(commentId);},10000);
    };

    /**
     * Called when voting ajax call has completed
     */
    var votingCompleteCallback = function(xhr, status){
        if (status=="success"){
            // write out the anonymous commentvote user cookie
            // using the value from the response header - expires after 1 year
            var anonId = xhr.getResponseHeader("CPLAT_COMMENT_VOTE_ANON_USER_ID");
            $.cookie('CPLAT_COMMENT_VOTE_ANON_USER_ID', anonId, { expires: 365, path: '/' });
        }
    };


    /**
     * Do and AJAX POST of the vote to CPLAT (via the client)
     * @param useful - boolean true if voting useful
     */
//    function moderate(){
//       // if (moderateValidation()) {
////        var moderateDiv = $("#mplat-contentModeration");
////        var requestParameters = base.retrieveRequestParametersFromContainer(moderateDiv);
////        var commentId =  $("#mplat-contentModeration").find("input[name='mplat_resource_uuid']").val();
////        var url = p_oParams.moderationUrl + "?ajaxRequestURL=/createWorkRequest.do";
////        eval("var moderateSuccessCallbackProxy = function(data) {moderateSuccessCallback('" + commentId + "', data);};");
////        eval("var moderateErrorCallbackProxy = function(data) {moderateErrorCallback('" + commentId + "', data);};");
////        base.ajaxSubmit(self, url, "POST", requestParameters, moderateSuccessCallbackProxy, moderateErrorCallbackProxy);
//      //  }
//        return false;
//    };


//    /**
//     * Success callback from Ajax moderation POST
//     */
//    var moderateSuccessCallback = function(commentId, data){
//        $("#cplat-commentModeration"+commentId).html(data);
//        $("#cplat-commentModeration"+commentId).after("<label>Successfully saved</label>");
//    };
//
//    /**
//     * Error callback from Ajax moderation POST
//     */
//    var moderateErrorCallback = function(commentId, XMLHttpRequest, data){
//
//         var queryString = XMLHttpRequest.getResponseHeader("queryString");
//
//        if (queryString !=  null) {
//            if (queryString.indexOf("mplat-error_checkbox") != -1 && $("#mplat-reason"+commentId).get(0) !== undefined) {
//                $("#mplat-reason"+commentId).before("<label>" + base.getValidationMessages().mplat-reason + "</label>");
//           }
//
//            if (queryString.indexOf("mplat-error_note") != -1 && $("#mplat-note"+commentId).get(0) !== undefined) {
//                $("#mplat-note"+commentId).before("<label>" + base.getValidationMessages().mplat-notes + "</label>");
//            }
//        }
//
//    };
//
//
//    function moderateValidation() {
//
//            var commentId = $('form').find("input[name='mplat_resource_uuid']").val();
//            var valid = true;
//            if ($('form').find("input#mplat_remReasonOTH").attr("checked") != 'true' || $('form').find("input#mplat_remReasonABU").attr("checked") != 'true' || $('form').find("input#mplat_remReasonCOM").attr("checked") != 'true' || $('form').find("input#mplat_remReasonCOP").attr("checked") != 'true') {
//
//                alert("yo 1");
//                //$('form').find("#mplat-reason"+commentId).before("<label>" + base.getValidationMessages().mplat-reason + "</label>");
//                valid = false;
//            }
//            if ($('form').find("textarea#mplat_notes").val().length == 0 && $('form').find("input#mplat_remReasonOTH" + commentId).attr("checked")) {
//                alert("yo 2");
//                // $('form').find("#mplat-note"+commentId).before("<label>" + base.getValidationMessages().mplat-notes + "</label>");
//                valid = false;
//            }
//            return valid;
//
//    }


    
    return base;
};

/**
 * Title: BBCWORLDWIDE_CPLAT.ResetPassword
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description: Registration Screen to handle CPLAT Reset Password process
 * @author: NgAW1
 * @version: $Revision: $
 * @date: 10 June 2008 16:51:45
 */
 

/**
 * This define the BBCWORLDWIDE_CPLAT.ResetPassword class, which override the singleton object
 * from BBCWORLDWIDE_CPLAT.BaseObject
 * @param base {@link BBCWORLDWIDE_CPLAT.BaseObject}
 * @return  base {@link BBCWORLDWIDE_CPLAT.ResetPassword}
 */
BBCWORLDWIDE_CPLAT.ResetPassword = function(base, p_oParams) {
	
    base.setclientConfigParams(p_oParams);
	
	base.addValidation = function (oForm) {
      	$(oForm).validate({rules:base.getValidationRules(),
		                   messages:base.getValidationMessages()
						  });
			base.addPasswordStrength($(oForm).find("input[id='cplat_passwordReset']"));
	};


	
	return base;
};

$(document).ready(function() {
	// hook for the overlay login works on all anchors with class of cplat-login
	$('a.cplat-login-modal').click(function () {
        
		// The core client Config object literals to configure the Login Overlay object
		var clientConfigParameters = { 
			overlayImgLoader: 'http://www.topgear.com' + applicationRoot + "images/core/ajax-loader.gif",
			userDefinedOverLayDimension: {
				width: 297, 		// 346 width - 25px padding left - 24 padding right
				height: 337			// 383 width - 23 padding top - 23 padding bot
			},
			passionSiteCallBack: {
				successCallBack: TG_CPLAT.clientImplementSuccessCallBack,  
				errorCallBack: TG_CPLAT.clientImplementErrorCallBack,
				overlayCloseCallBack: TG_CPLAT.clientImplementOverlayCloseCallBack
			}
     };

		// set the login URLs to ajax urls
		$(this).attr('href', applicationRoot + 'ajaxlogin');
		
		// Create the login Overlay object
		// note: using AjaxOverLayScreenManager object and the handleLinkClick in order to get an overlay page
		BBCWORLDWIDE_CPLAT.LoginOverlay(BBCWORLDWIDE_CPLAT.AjaxOverLayScreenManager, clientConfigParameters).handleLinkClick(this);
		
		return false;
	});
});
	
// namespace for TG specific CPLAT functions
var TG_CPLAT = TG_CPLAT || {};

TG_CPLAT.clientImplementSuccessCallBack = function(p_param) {
	window.location.reload();
};
TG_CPLAT.clientImplementErrorCallBack = function(p_param) {
	window.location = applicationRoot + 'login';
};
TG_CPLAT.clientImplementOverlayCloseCallBack = function() {

};
