// MF US Question script
var LandingQuestionPage = function(){
	var cookieKey = 'questions';
	var lastQuestionSign = "msisdn";
	var questionSize = 0;

	var isHistoryEnable = true;
	var currQuestionIndex;
	var isLastQuestionProcessing = false;
	
	function init(){
		if(questionXML_JSON && questionXML_JSON.questionArray && questionXML_JSON.questionArray.length>0){
			questionSize = questionXML_JSON.questionArray.length;
		} else {
			$j(window).unbind("unload");
			window.location=actionInputPath;
		}
		// for the first page
		currQuestionIndex = setCurrQuestionIndex();
		
		if(isHistoryEnable){
			if(currQuestionIndex == ''){
				location.hash = "1";
			}
			// history function
			$j(document).ready(function(){
				$j.historyInit(LandingQuestionPage.nextQuestion);
			});
			// end history function
			
		} else {
			if(currQuestionIndex == ''){
				$j(window).unbind("unload");
				window.location = location.pathname+'?1';
			} else {
				LandingQuestionPage.nextQuestion(currQuestionIndex);
			}
		}
		
	}
	
	function setCurrQuestionIndex(){
		if(isHistoryEnable){
			var hash = location.hash;
			return hash.replace('#','');
		} else {
			return getTheFirstURLParam();
		}
	}

	/**
	 * jump to next question
	 */
	function nextQuestion(questionNum) {
		
		 // to solve safari and firefox history back
		 if(!questionNum || questionNum==""){
			jumpToFirstQuestion();
		 } 
		if(questionNum && (parseInt(questionNum)<= questionSize)) {
			$j("#question_zone").empty();
		 	LandingQuestionPage.changeQuestion(parseInt(questionNum));
		 } else if(questionNum && (questionNum== lastQuestionSign)){
		 	if(isHistoryEnable){
		 		if(!isLastQuestionProcessing){
				 	// back from gender page
					jumpToFirstQuestion();
		 		} else {
		 			// submit the question data to gender page
					$j("#questionsAnswerJSON").val(jaaulde.utils.cookies.get(cookieKey));
					$j(window).unbind("unload");
					$j("#questionForm").submit();
					return;
		 		}
		 	}
		 }
		 
		isLastQuestionProcessing = false;
	}
	
	function jumpToFirstQuestion(){
		$j("#question_zone").empty();
	 	location.hash = "1";
	 	LandingQuestionPage.changeQuestion(1);
	}
	
	function getTheFirstURLParam(){
		var urlquery=location.href.split("?");
		if(urlquery[1]){
			var urlParam=urlquery[1].split(",");
			if(urlParam && urlParam[0]){
				return urlParam[0];
			} 
		}
		return "";
	}
	
	function isAnswerSelected(){
		// don't check it if there are no radio button
		if($j("input[name=selectans]").length == 0){
			return true;
		}
		var selectedAnswer = $j("input[name=selectans]:checked");
		if(!selectedAnswer || selectedAnswer.length==0){
			return false;
		}
		return true;
	}
	
	function changeQuestion(toQuestionNum){
		// add question option
		var questionArray = questionXML_JSON.questionArray;
		var questionJSON = questionArray[toQuestionNum-1];
		var title = questionJSON.title;
		// add question title
		QUESTION_TEMPLATE.getQuestionTemplate.append($j('#question_zone'),{questionNum:toQuestionNum,questionTitle:title,numOfQuestion:questionSize});
		
		var optionsJSONArray = questionJSON.optionArray;
		var nextQuestionNum;
		if(toQuestionNum == questionSize){
			nextQuestionNum = lastQuestionSign;
		} else {
			nextQuestionNum = toQuestionNum+1
		}
		
		var questionHref = "javascript:void(0)";
		
		for(var i=0; i<optionsJSONArray.length; i++){
			QUESTION_TEMPLATE.getOptionTemplate.before($j('#inputbutton'),{
					id:optionsJSONArray[i].id 
					,questionNum:toQuestionNum
					,content:optionsJSONArray[i].content
					,numOfOption:i+1
					,nextQuestionNum:nextQuestionNum
					,questionHref:questionHref
				});
		}

		if(isHistoryEnable){
			//Forcing Safari to Re-render the select box option list
			if ($j.browser.safari) {
				$j("#answers").css("display","none");
				setTimeout(function(){
					$j("#answers").css("display","");
				},1);
			}

			if(!($j("#inputbutton")) || $j("#inputbutton").css("display") == 'none'){
				for(var i=0; i<optionsJSONArray.length; i++){
					var answerNum = i+1;
					$j(".ans"+answerNum).click(
						function(){						
							if(!isAnswerSelected()){
								alert(JsResourceMap.selectAnswer);
								 return false;
							}
							LandingQuestionPage.doQuestion(toQuestionNum,
								function(){
									$j.historyLoad(location.hash.replace('#', ''));
								}
							);
						}
					);
				}
			}else{
				$j("#nextQuestionBtn").click(
				    function(){
				    	if(!isAnswerSelected()){
							alert(JsResourceMap.selectAnswer);
							 return false;
						}
						LandingQuestionPage.doQuestion(toQuestionNum);
				        $j.historyLoad(location.hash.replace('#', ''));
				});
			}
		}
	}
	
	function doQuestion(num, callback){
		// block double-request when the last question is processing.
		if(isLastQuestionProcessing){
			return;
		}
		var selectedAnswer = $j("input[name=selectans]:checked").attr('answer');
		if(!selectedAnswer){
			// get hidden field
			selectedAnswer = $j("#hiddenAnswer").val();
		}
		
		createCookie(num, selectedAnswer);
		currQuestionIndex = setCurrQuestionIndex();
		
		
		if(currQuestionIndex == questionSize) {
			isLastQuestionProcessing = true;
			if(isHistoryEnable){
				location.hash = "#"+lastQuestionSign;
			} else {
				// submit the question data to gender page
				$j("#questionsAnswerJSON").val(jaaulde.utils.cookies.get(cookieKey));
				$j(window).unbind("unload");
				$j("#questionForm").submit();
			}
		} else {
			if(isHistoryEnable){
				location.hash = "#"+(parseInt(currQuestionIndex)+1);
			} else {
				$j(window).unbind("unload");
				window.location=actionQuestionPath+'?'+(parseInt(currQuestionIndex)+1);
			}
		}
		if(callback){
			callback();
		}
	}
	
	function createCookie(num, answer){
		var questionsCookie = jaaulde.utils.cookies.get(cookieKey);
		var cookieQuestionsJSON = new Object();
		// create a JSON Object for question answer
		var questionJSON = new Object();
		questionJSON.num = num;
		questionJSON.answer = answer;
		
		var questions = new Array();
		
		var isNewCookie = false;

		if(questionsCookie){
			questionsCookie = JsonHelper.decode(questionsCookie);

			if(questionsCookie.landingId == landingId && questionsCookie.questions && questionsCookie.questions.length > 0){
				cookieQuestionsJSON.landingId = landingId;
				questions = addUniqueQuestionAnswer(questionsCookie.questions, questionJSON);
				cookieQuestionsJSON.questions = questions;
			} else {
				isNewCookie = true;
			}
		} else {
			isNewCookie = true;
		}
		if(isNewCookie){
			// the first question Answer
			cookieQuestionsJSON.landingId = landingId;
			questions.push(questionJSON);
			cookieQuestionsJSON.questions = questions;
		}
		var options = {
			path: '/',
			//domain:  window.location.hostname,
			hoursToLive: 1
		};
		jaaulde.utils.cookies.set(cookieKey,JsonHelper.encode(cookieQuestionsJSON) , options);
	}
	
	
	function addUniqueQuestionAnswer(questions, questionJSON){
		var questionNum = questionJSON.num;
		var existingQuestionIndex = -1;

		for(var i=0; i<questions.length; i++){
			if(questions[i].num == questionNum){
				existingQuestionIndex=i;
				break;
			}
		}	
		if(existingQuestionIndex != -1){
			// existing question answer
			questions.splice(existingQuestionIndex, 1, questionJSON);
		} else {
			// not existing question answer
			questions.push(questionJSON);
		}
		return questions;
	}
	
	function getNumOfFinished(questionsCookie){
		var num = 0;
		
		if(!questionsCookie || (!questionsCookie.questoins)){
			return num;
		}
		return questionsCookie.questoins.length;
	}
	
	return {
		init : function() {	
			init();
		} ,doQuestion : function(num, callback) {	
			doQuestion(num, callback);
		} ,changeQuestion: function(questionNum){
			return changeQuestion(questionNum);
		} , nextQuestion : function(questionNum){
			return nextQuestion(questionNum);
		}
	};
		
}();
// End MF-US Question script
	
var LandingPinPage = function() {
	var alertId = 'alert';
	var submitBtnId = 'btn_go';
	var termsId = 'terms';
	var tosLinkId = 'tos';
	var tosText = '';
	
	var errorMsg = '';
	
	function checkPin(pwdVal) {
		var pattern = /\d{4}/;
		return ((pwdVal == '') || (!pattern.test(pwdVal))) ? false : true;
	}
	
	function validatePin(formObj) {
		errorMsg = '';
		var error = false;
		if (!checkPin(formObj.elements['password'].value)) {	
			errorMsg += "- "+JsResourceMap.passwordDigitError+"\n";
			error = true;
		}
		if (error) {
			formObj.elements['password'].select(); 
		}else{
			btn = document.getElementById(submitBtnId);
			if(btn){
				btn.disabled=true;
			}
		}
	}
	
	function submitPin(){
		var termsCheckBox = document.getElementById(termsId);
		if(termsCheckBox && !termsCheckBox.checked ){
			errorMsg += "- "+JsResourceMap.signupTermsError+"\n";	
			termsCheckBox.focus();
		} 
		if(errorMsg && errorMsg.length>0){
			alert(JsResourceMap.errorHeader + "\n\n" + errorMsg + "\n" + JsResourceMap.errorFooter);
			return false;
		}
		$j(window).unbind("unload");
		return true;
	}
	
	function toShow(obj_id) {
		$j("#"+obj_id).css("display","");
	}
	
	function toHide(obj_id) {
		$j("#"+obj_id).css("display","none");
	}
	
	function checkAlert(){
		if(this.checked){
			toHide(alertId);
		}
	}
	
	function initPinTimer(){
		var secs;
		var timerID = null;
		var timerRunning = false;
		var delay = 1000;
		InitializeTimer();
		function InitializeTimer()
		{
			// Set the length of the timer, in seconds
			secs = 15;
			StopTheClock();
			StartTheTimer();
		}
		
		function StopTheClock()
		{
			if (timerRunning){
				clearTimeout(timerID)
			}
			timerRunning = false
		}
		
		function hidediv() {
			document.getElementById('inputtext2').style.display = 'none';
			document.getElementById('inputtext3').style.display = '';						
		}
		
		function StartTheTimer()
		{
			if (secs == 0)
			{
				StopTheClock();
				hidediv();
				//alert("You have just wasted 10 seconds of your life.")
			}
			else
			{
				secs = secs - 1;
				timerRunning = true;
				timerID = self.setTimeout(function(){StartTheTimer()},delay);
			}
		}
		
	}	
	
	function initEvent(){
		$j('#'+termsId).click(checkAlert);
	}
	function initTooltip(){
		//Query for init tnc link to display tnc in the big jquery tooltip box
		$j("#"+tosLinkId).tooltip({
			bodyHandler: function() { 
				return tosText; 
			}, 
			track: true, 
			showURL: false, 
			left: -650,
			extraClass: "tandc"
		});		
	}
	
	return {
		init : function(config) {
			if(config.alertId){
				alertId = config.alertId
			}
			if(config.submitBtnId){
				submitBtnId = config.submitBtnId
			}
			if(config.termsId){
				termsId = config.termsId
			}
			if(config.tosLinkId){
				tosLinkId = config.tosLinkId
			}
			if(config.tosText){
				tosText = config.tosText
			}						
			// initTooltip();
			initPinTimer();
			initEvent();
									
		},
		validatePin: function(formObj){
			validatePin(formObj);
			return submitPin();
		}
	};
}();	

var LandingRegisrationPage = function(){
	
	function checkLeadingZero(obj){
		var phoneObj = document.getElementById('msisdn.phone');
	    var msisdn = phoneObj.value;
	    if (msisdn.length == 12 && msisdn.charAt(0) != '0') {
	        return false;
	    }
	    return true;
	}
	
	function checkPhone(obj) {
	    var a = document.getElementById('areacode').value;
	    var p = document.getElementById('prefix').value;
	    var s = document.getElementById('suffix').value;
	   
	    var phone = a + p + s;
	    var pattern = /\d{10}/;
	    if (pattern.test(phone)) {
	        return true;
	    }
	    return false;
	}
	
	function checkOperator(obj) {
	    var o = obj.elements['operatorId'].value;
	
	    if (o > 4) {
	        return true;
	    }
	    return false;
	}
		
	function checkRegister(obj) {
	    var error = false;
	    var msg = '';
	
        if (!checkPhone(obj)) {
            msg = msg + "- "+JsResourceMap.signupWarningMsisdn+".\n";
            error = true;
        }
        if(obj.elements['operatorId']!=undefined && !checkOperator(obj)){
            msg = msg + "- "+JsResourceMap.signupWarningOperator+".\n";
            error = true;        
        }
	   
	    if (error) {
	        alert(JsResourceMap.signupWarningHeader + msg + JsResourceMap.signupWarningFooter);
	        return false;
	    }else if (!checkYellowCheckBox(obj)){
	    	return false;
		}else{
	    	disPopup();
	    	return true;
	    }
	}
	
	function checkYellowCheckBox(obj) {
	    var error = false;
	    var msg = '';
	    var checked = document.getElementById(obj.id + '_terms');
	    if (checked && checked.checked == false) {
	        error = true;
	    }
	    if (error) {
	        document.getElementById('alert').style.display = '';
	        return false;
	    }else{
	    	disPopup();    	
	    	return true;
		}
	}
	
	function disPopup() {
	    document.body.onunload = "";
	    window.onunload = "";
	    $j(window).unbind("unload");
	}
	
	function addLeadingZeroEvent(){
		var msisndDOM = document.getElementById("msisdn.phone");
		if(msisndDOM){
			$j(msisndDOM).keydown(
				updateZeroLeadingField
			);
			$j(msisndDOM).keyup(
				updateZeroLeadingField
			);
		}

	}

	function updateZeroLeadingField (){
		var msisdn = document.getElementById("msisdn.phone").value;
		var jqueryMsisdn = $j(document.getElementById("msisdn.phone"));
		if(msisdn.charAt(0)==0){
			jqueryMsisdn.attr("maxlength","12");
		} else {
			jqueryMsisdn.attr("maxlength","11");
		}
	}
	return {
		checkRegister : function(obj){
			return checkRegister(obj);
		} , addLeadingZeroEvent : function(){
			return addLeadingZeroEvent();
		} 
	};
}();

var LandingCommon = function(){
	function unloadPopup(link) {
	    //var Popup = window.open('/popup/countdown.html','','height=420,width=760,status=0,toolbar=0,menubar=0,location=0');
	    var Popup = window.open(link, '', 'height=420,width=760,status=0,toolbar=0,menubar=0,location=0,scrollbars=1');
	    if (Popup != null)
	    	Popup.focus();
	}

	function checkCampaignStatus(landingId) {
		var result = {
			url: "/verify.jsp",
			dataType: "json",
		    success: function(dataJson) {
		        if(dataJson){
		        	if (dataJson.status == 1){
		        		$j("#key").val(dataJson.key);
		        		$j("#pixel").val(dataJson.pixel);

		        		document.getElementById("verifyform").submit();
		        	}
		        	else
		        		setTimeout('LandingCommon.checkCampaignStatus('+landingId+')', 20000);
		        } else
		        	setTimeout('LandingCommon.checkCampaignStatus('+landingId+')', 20000);
		    },
	    	error: function(o) {
	           	setTimeout('LandingCommon.checkCampaignStatus('+landingId+')', 20000);
		    }
		};
		
	   	$j("#verifyform").ajaxSubmit(result);
	}

	function useKey(key) {
		location.href = "http://dev.us89614mf.mobilefirst.com/wswelcome!input.do?key=" + key;
	}
	
	function reWriteTNCLink(value) {
		var tncPagePattern = "/fullTnC.jsp";;
		var privacyPagePattern = "/fullPrivacy.jsp";	
		var aTags = $j("a");
		for(var i=0; i<aTags.length; i++){
			var aTag = aTags[i];
			if (endWith(aTag.href,tncPagePattern) || endWith(aTag.href,privacyPagePattern)){
				var updatedHref = aTag.href+"?l="+value;
				$j(aTag).attr("href",updatedHref);
			}
		}
	}
	
	function endWith(s1,s2)  
	{  
		if(s1.length<s2.length)  
			return   false;  
		if(s1==s2)  
			return   true;  
		if(s1.substring(s1.length-s2.length)==s2)  
			return   true;  
		return   false;  
	}
	
	
	return {
		unloadPopup : function(link) {	
			unloadPopup(link);
		}, checkCampaignStatus : function(landingId) {	
			checkCampaignStatus(landingId);
		}, useKey: function(key){
			return useKey(key);
		}, reWriteTNCLink: function(value){
			return reWriteTNCLink(value);
		} 
	};
}();

$j(document).ready(function() {			
	LandingRegisrationPage.addLeadingZeroEvent();
});
