Event.observe(window, 'load', function () {

new ccPreApply();

});


// -----------------------------------------------------------------------------------

var ccPreApply = Class.create();

ccPreApply.prototype = {

	initialize: function() {

		this.cardUrl = escape(window.location);
		this.cardVersion = this.cardUrl.split("/")[3];
		this.cardSelectErrorMessage = "Please choose a card type from the options above.";
		this.summaryBoxErrorMessage = "Please tick the box to indicate you have read the summary box"
		this.errorCross = "/virgin/Images/cross_tcm23-4889.gif";
		this.cardSelected = false;
		this.cardRateForm = $("rateForm");
		this.cardColourForm = $("colourForm");
		this.validForm = $("validForm");
		this.verifyCheck = $("verify");
		this.selectedCardSourceCode = "";
		this.applyLink = $("bt-credit-card-apply-link");
		this.summaryBoxLink = $("summary-box-link")
		this.option1 = $("option1");
		this.option2 = $("option2");
		this.option1SummaryURL = "popup/summary-option1.jsp";
		this.option2SummaryURL = "popup/summary-option2.jsp";
		this.findCCPreApplyPage();

	},


	findCCPreApplyPage: function() {

		if($("bt-credit-card-apply-link")) {

		this.activateCCPreApplyPage();

		}

	},

	activateCCPreApplyPage: function() {

		this.summaryBoxErrorHide();
		this.cardSelectedErrorHide();
		this.checkSelectedCard();
		this.selectedCardOnload();
		Event.observe(this.option1,'click',this.processCardSelection.bindAsEventListener(this, this.option1SummaryURL, false));
		Event.observe(this.option2,'click',this.processCardSelection.bindAsEventListener(this, this.option2SummaryURL, false));
		Event.observe(this.applyLink,'click',this.preApplyPageApply.bindAsEventListener(this));
		Event.observe(this.verifyCheck,'click',this.summaryBoxErrorHide.bindAsEventListener(this));

	},

	selectedCardOnload: function() {

		rateInputId = false;

		rateRadioSet = this.cardRateForm.rate;
		rateRadioLength = rateRadioSet.length

		for(i=0;i<rateRadioLength;i++) {

			if(rateRadioSet[i].checked) {

				rateInputId = rateRadioSet[i].id;

				if(rateInputId == "option1") {

					this.processCardSelection(this, this.option1SummaryURL, rateInputId);
				}

				if(rateInputId == "option2") {

					this.processCardSelection(this, this.option2SummaryURL, rateInputId);
				}

			}
		}


		radioSet = this.cardColourForm.productCode;
		radioLength = radioSet.length;

		for(i=0;i<radioLength;i++) {
			if(radioSet[i].checked) {
				inputId = radioSet[i].id
			}
		}

		$(inputId).onchange();

	},

	checkSelectedCard: function() {

		($("option1").checked || $("option2").checked) ? $("box-3").show() : $("box-3").hide();


	},

	preApplyPageApply: function(e) {

		if(this.verifyCheck.checked && this.cardSelected) {

			this.rewriteFormColourValue();
			this.rewriteFormAction();

		} else {

			if (!this.cardSelected) {

				this.cardSelectedErrorShow();

			}

			if (!this.verifyCheck.checked) {

				this.summaryBoxErrorShow();

			}

		}

	},

	processCardSelection: function(e,url, id) {

		new Effect.Appear($("box-3"));
		this.cardSelectedErrorHide();
		this.cardSelected = true;
		this.changeSummaryLinkURL(url);
		this.changeCardSourceCode(e, id);




	},

	cardSelectedErrorHide: function() {

		$$(".card-select-error").each(function(s){s.update().hide()})
		$("card-select-error-message").update().hide();

	},

	cardSelectedErrorShow: function() {

		$$(".card-select-error").each(function(s){

			s.show();
			s.update("<img alt=\"error\" src=\""+ this.errorCross +"\"/>")

		}.bind(this));

		$("card-select-error-message").update("<img alt=\"error\" src=\""+ this.errorCross +"\"/>"+ this.cardSelectErrorMessage).show();

	},

	summaryBoxErrorHide: function() {

		$("errormark").update().hide();
		$("summary-box-error-message").update().hide();

	},

	summaryBoxErrorShow: function() {

		$("errormark").update("<img alt=\"error\" src=\""+ this.errorCross +"\"/>").show();
		$("summary-box-error-message").update("<img alt=\"error\" src=\""+ this.errorCross +"\"/>"+ this.summaryBoxErrorMessage).show();

	},

	changeSummaryLinkURL: function(url) {

		this.summaryBoxLink.href=url;
		this.activatePopup(this.summaryBoxLink);

	},

	changeCardSourceCode: function(event, id) {

		if(id) {

			clickedElement = $(id);

		} else {

			clickedElement = Event.element(event);

		}

		this.selectedCardSourceCode = clickedElement.value;


	},


	returnCookieStatus: function(cookieStr) {

		var cookieString = document.cookie;
		cookieBannerPos = cookieString.indexOf(cookieStr);

		if (cookieBannerPos !=-1 ) {
			cookieBannerString = cookieString.slice(cookieBannerPos);
			cookieBannerArray = cookieBannerString.split(";");
			cookieBannerParam = cookieBannerArray[0];
			cookieBannerValue = getValueFromParameter(cookieBannerParam)
			return true;

		} else {

			return false

		}
	},

	getCookieValue: function(cookieLabel){

		var cookieString = document.cookie;
		cookieStrPos = cookieString.indexOf(cookieLabel);
		if (cookieStrPos !=-1 ) {

			if (cookieString.indexOf(';') !=-1) {

				ourCookieString = cookieString.slice(cookieStrPos);
				cookieArray = ourCookieString.split(";");
				cookieValue = (cookieArray[0]).split("=")[1];
				return cookieValue;

		   	}

		} else {

			return "";

		}
	},

	rewriteFormColourValue: function() {

		radioSet = this.cardColourForm.productCode;
		radioLength = radioSet.length;

		for(i=0;i<radioLength;i++) {
			if(radioSet[i].checked) {
				selectedValue = radioSet[i].value;
			}
		}

		this.validForm.productCode.value = selectedValue;


	},

	rewriteFormAction: function() {

		formAction = this.validForm.action.toString();
		var formActionArray = formAction.split('?'); //Everything after the ?
		var formActionUrl = formActionArray[0];
		var formActionParams = formActionArray[1]


		if (this.selectedCardSourceCode !="") {

			selectedSourceCode = this.selectedCardSourceCode;
			sourceCodePos = formActionParams.indexOf('sc=')
			sourceCodeString = (formActionParams.slice(sourceCodePos)).split("&")[0].split("=")[1]
			newFormAction = formAction.replace(sourceCodeString,selectedSourceCode)
			formAction = newFormAction;

		}

		if (this.returnCookieStatus('source=')) {

			bannerCodePos = formActionParams.indexOf('mc=');
			bannerCodeString = ((formActionParams.slice(bannerCodePos)).split("&")[0]).split("=")[1]

			cookieBannerCode = this.getCookieValue("source");
			newFormAction = formAction.replace(bannerCodeString,cookieBannerCode)

		}

		params="";

		//for (var values in this.webtrendValues) {

			//params+= values +"," + this.webtrendValues[values] +","; //rewrites the object in the correct string format

	   	//}


	   	//params = params.substr(0,params.length-1);
	   	//paramsArray = params.split(",");
	   	//dcsMultiTrackArray(params);


		this.validForm.action = newFormAction;

		this.validForm.submit();


	},

	activatePopup: function(element) {

	Event.stopObserving(element, 'click');
	popupAttr = this.extractPopupAttributes(element);
	popupUrl = element.href;
	popupId = element.id+"-popup";
	element.writeAttribute("onclick", "return false");
	Event.observe(element,'click', function(event){Event.stop(event);});
	Event.observe(element,'click', this.openPopup.bindAsEventListener(this, popupUrl, popupId, popupAttr));


	},

	extractPopupAttributes: function(id) {

			popupStr = $(id).rel;
			popupStrSpl = popupStr.split("[");
			popupStrSpl = popupStrSpl[1].split("]");
			popupAttr = popupStrSpl[0].split(",");

			return popupAttr;

	},

	closePopup: function() {

		return true;

	},

	openPopup: function(e, url,WinName,attr) {

		   this.closePopup();

		   // Set defaults according to the old function's settings
		   var defaultParamObj = {
		      resizable:'yes',
		      toolbar:'no',
		      scrollbars:'yes',
		      menubar:'yes',
		      status:'yes'
		      }
		   var params = ",";

		   if(attr[2]) { // Checks to see if the fifth parameter exists

		      var obj    = attr[2];

		      for (var prop in obj) { //Loops through the values in the object

			 defaultParamObj[prop] = obj[prop];  // replace defaults as necessary
		      }
		   }


		   for (var defaultProp in defaultParamObj) {

		      params+= defaultProp +"=" + defaultParamObj[defaultProp] +","; //rewrites the object in the correct string format

		   }

		   params = params.substring(0,params.length-1); //remove the comma at the end of the string

		   var winl = (screen.width - attr[0]) / 2;
		   var wint = (screen.height - attr[1]) / 2;
		   winprops = 'height='+attr[1]+',width='+attr[0]+',top='+wint+',left='+winl+params;

		   this.NewWin = window.open(url,null,winprops);
		   this.NewWin.focus();

	},

	webtrendValueForSubmit: function() {

		if (arguments.length%2==0){

			for (var i=0;i<arguments.length;i+=2){

				if (arguments[i].indexOf('WT.')==0){
					WT[arguments[i].substring(3)]=arguments[i+1];
				}
				else if (arguments[i].indexOf('DCS.')==0){
					DCS[arguments[i].substring(4)]=arguments[i+1];
				}
				else if (arguments[i].indexOf('DCSext.')==0){
					DCSext[arguments[i].substring(7)]=arguments[i+1];
				}

			}
		}

	}

};