/* cache css bg images for IE6 */
if (document.all) {
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {
    }
}

if(navigator.userAgent.toLowerCase().indexOf('Safari') != -1 && location.href.indexOf('destination')!= -1){document.write('<style>p.rail_text{text-decoration: none;}a #destvideo_rail{text-decoration: none;}</style>');}
//convenience fn creates new controller object and calls triggerSendRequest
var sendToPhoneInstance = undefined;

function sendtophone(elementId, itemTitle, destinationId, productType, productId) {
	if (sendToPhoneInstance == undefined) {
		sendToPhoneInstance = new SendToPhoneController();	
	}
    sendToPhoneInstance.initPhoneBox(elementId, itemTitle, destinationId, productType, productId); //productId is optional
}

var SendToPhoneController = Class.create();
SendToPhoneController.prototype = {
    PRODUCT_ID_PARAM : "productId",
    PRODUCT_TYPE_PARAM : "productType",
	DESTINATION_ID_PARAM: "destinationId",
    RETURN_TO_PARAM: "returnToURL",
    DESTINATION_INFO_ID: "title_destination",
	TITLE_FIRSTPART_ID : "title_firstpart",
	TITLE_SECONDPART_ID: "title_secondpart",
	CONTROL_ERROR_ID: "sms_error_popup_info",
	HIDE_CONTENT_ID: "hide_content",

	_elementId: undefined,
	_itemTitle: undefined,
	_destinationId: undefined,
	_productType: undefined,
	_productId: undefined,
	    
    GET_PROFILE_PHONE_NUMBER_AJAX_URL: "/ajax/sendToPhone",
    SEND_TO_PHONE_SUBMIT_AJAX_URL: "/ajax/sendToPhoneSubmit",

	COOKIE_NAME_PHONE : "phone",
    COOKIE_NAME_PROVIDER_ID : "providerId",
    COOKIE_NAME_SHOW_BOX : "showbox",
	COOKIE_NAME_JSESSIONID : "JSESSIONID",

    RESPONSE_CODE_OK: "OK",
    RESPONSE_CODE_ERROR_PARAMS: "FAIL_PARAMS",
    RESPONSE_CODE_ERROR_LOGIN: "FAIL_LOGIN",
    RESPONSE_CODE_ERROR_GENERAL: "FAIL_GENERAL",

    RESPONSE_EXCEPTION_PROP : "exception",
    PROCESSING_ERROR: "Your request did not go through.  Please try again.",
	CONCURRENT_REQUEST_ERROR: "We are currently sending an item to your phone. Only one item can complete concurrently. Please wait . . .",
	SEND_TO_PHONE_SUCCESS : "Message sent successfully.",
	MESSAGE_PHONE_ERROR : "Invalid US phone number.",
	MESSAGE_CARRIER_ERROR : "Please select a carrier.",
	MESSAGE_SENDING: "Sending . . .",
	MESSAGE_TITLE_FIRSTPART: "Send ",
	MESSAGE_TITLE_SECONDPART: " to your phone!",
	MESSAGE_TITLE_SECONDPART_SUCCESS: " has been sent!",

    requestActive: false,
    statusMessageActive: false,
	conciergeRootURL: "http://" + window.location.host,
    ajaxRequestRef: undefined,
    sendToPhoneRespons: undefined,
	popUpTimeOut: undefined,
	TIME_OUT_LENGTH: 5 * 1000,  // 5 seconds time out

    initialize: function() {
	    //Event.observe(document.body, "onscroll",  this.scrollProgressMessage.bindAsEventListener(this) ); 
	    //Event.observe(document.body, "DOMMouseScroll",  this.scrollProgressMessage.bind(this) ); 
	    //window.onmousewheel = document.onmousewheel = this.scrollProgressMessage.bindAsEventListener(this);
	   
    },
    
	buildConciergeURL: function(path) {
        return (this.conciergeRootURL + path);        
    },
    
    showError: function(errorMessage) {
		this.hideContentPopupLayout(false);
		this.showMessage(this.CONTROL_ERROR_ID, errorMessage);
		//If there is any error occured, show box should be unchecked
		this.checkShowBox(false);
		this.displayPopupLayout(true);
    },

    showMessage: function(domId, message) {
		var messageSpan = $(domId);
		if (messageSpan.lastChild){
			messageSpan.removeChild(messageSpan.lastChild);
		}
		var message = document.createTextNode(message);
		messageSpan.appendChild(message);
    },

	showInitialTitle: function () {
		this.showMessage(this.TITLE_FIRSTPART_ID, this.MESSAGE_TITLE_FIRSTPART);
		this.showMessage(this.DESTINATION_INFO_ID, this._itemTitle);
		this.showMessage(this.TITLE_SECONDPART_ID, this.MESSAGE_TITLE_SECONDPART);
	},

	showConfirmationTitle: function () {
		this.showMessage(this.CONTROL_ERROR_ID, "");
		this.showMessage(this.TITLE_FIRSTPART_ID, "");
		this.showMessage(this.DESTINATION_INFO_ID, this._itemTitle);
		this.showMessage(this.TITLE_SECONDPART_ID, this.MESSAGE_TITLE_SECONDPART_SUCCESS);
	},

	clearPopUpMessage: function (domId) {
		var messageSpan = $(domId);
        if (messageSpan != null) {
    		if (messageSpan.lastChild){
    			messageSpan.removeChild(messageSpan.lastChild);
    		}
        }
	},

	startPopUpTimeout: function () {
		this.popUpTimeOut = setTimeout("sendToPhoneInstance.displayPopupLayout(false)", this.TIME_OUT_LENGTH);
	},

	stopPopUpTimeOut: function () {
		clearTimeout(this.popUpTimeOut );
	},

    initPhoneBox: function(elementId, itemTitle, destinationId, productType, productId) {    
        if (this.requestActive) {
            //abort, request is already occurring
            this.showError(this.CONCURRENT_REQUEST_ERROR);
            return;
        }
        
		//Clear pop-up time out
		this.stopPopUpTimeOut();
		//Clear pop-up message if there is any
		this.clearPopUpMessage(this.CONTROL_ERROR_ID);

		this._elementId = elementId;
		this._itemTitle = itemTitle;
		this._destinationId = destinationId;
		this._productType = productType;
		this._productId = productId;

		if (this.isShowBox()) {        
			this.hideContentPopupLayout(false);
			this.displayPopupLayout(true);
            if (!this.isSendToPhoneCookieSet()) {
				//calling the first ajax request
                this.getProfilePhoneNumberAjaxRequest();
            } else {
                //use cookie value instead of getting from server
				this.populateSendToPhoneField(this.getCookiePhone(), this.getCookieProviderId());
            } 
        } else {
			//Show message box is checked, so we populate form fields with cookies value and then send the request right away
			this.populateSendToPhoneField(this.getCookiePhone(), this.getCookieProviderId());
			this.hideContentPopupLayout(true);
			this.displayPopupLayout(true);
            this.triggerSubmitRequest();
        }     
    }, 

	getProfilePhoneNumberAjaxRequest: function () {
        var submitURL = this.buildConciergeURL(this.GET_PROFILE_PHONE_NUMBER_AJAX_URL);
        //set parameters for this request
        var opt = {
            method: 'post',
            //parameters: queryString,
            //onSuccess: this.onSuccess.bind(this),
            onComplete: this.onCompleteGetProfilePhoneNumber.bind(this),
            onFailure: this.onFailureGetProfilePhoneNumber.bind(this)
            //onException: this.onException.bind(this)
        }

		this.requestActive = true; //ensures only single add at a time
        this.ajaxRequestRef = new Ajax.Request(submitURL, opt);
	},

    onCompleteGetProfilePhoneNumber: function(response) {
        if (response.readyState == 4) { // Complete
			if (response.status == 200) { // OK response
				responseValue=response.responseText;
				var json = eval("(" + response.responseText + ")");
				if (json != undefined) {
					var varPhone = (json.phone == undefined ? "":json.phone);
					varPhone = this.decrypteStr(varPhone);
					var varProviderId = (json.providerId == undefined ? "" : json.providerId);
					this.populateSendToPhoneField(varPhone, varProviderId);
					if (varPhone != "" && varProviderId != "") {
						//set value into cookies
						this.setSendToPhoneCookie(varPhone, varProviderId);
					}
				}        
			} else {
				this.onFailureGetProfilePhoneNumber(response);
			}        
        } else {
			this.onFailureGetProfilePhoneNumber(response);
		}

		this.requestActive = false;
    },	

    onFailureGetProfilePhoneNumber: function(response) {
        this.requestActive = false;
		//Even if we failed to get the phone number, we still show the pop-up with blank phone information.
		//this.displayPopupLayout(false);
    },

    triggerSubmitRequest: function () {
        if (this.checkSendToPhoneField()) {
			this.concatenatePhoneNumber();
			//var phone = this.encrypteStr(document.sendForm.phoneNumber.value);
			var phone = encodeURIComponent(this.encrypteStr(document.sendForm.phoneNumber.value));
			var providerId = document.sendForm.phoneProvider.options[document.sendForm.phoneProvider.selectedIndex].value;
			var strParameter = "?" + "phone=" + phone + "&providerId=" + providerId;
			strParameter = strParameter + "&destinationId=" + this._destinationId + "&productType=" + this._productType;
			if (this._productId != undefined)
				strParameter = strParameter + "&productId=" + this._productId;
			var submitUrl  = this.buildConciergeURL(this.SEND_TO_PHONE_SUBMIT_AJAX_URL);
            // send message through ajax along with parameters.
            this.sendToPhoneSubmitAjaxRequest(submitUrl + strParameter);      
        } 
    },

    sendToPhoneSubmitAjaxRequest: function (url) {
        var opt = {
            method: 'post',
			onFailure: this.onFailureSendtophoneSubmit.bind(this),
            onComplete: this.onCompleteSendtophoneSubmit.bind(this)
        }
		this.requestActive = true; //ensures only single add at a time
		this.showMessage(this.CONTROL_ERROR_ID, this.MESSAGE_SENDING);
        this.ajaxRequestRef = new Ajax.Request(url, opt);       
    },

    onCompleteSendtophoneSubmit: function (response) {
        if (response.readyState == 4) { // Complete
			if (response.status == 200) { // OK response        
				var json = eval("(" + response.responseText + ")");
				if (json == undefined) {
					this.onFailureSendtophoneSubmit(response);
				} else {
					var responseMessage = (json.responseMessage == undefined ? "":json.responseMessage);
                
					//set phone number and provider into cookies if the message has been sent successfully.
					if (json.responseSuccess) {
						this.setSendToPhoneCookie(document.sendForm.phoneNumber.value, document.sendForm.phoneProvider.options[document.sendForm.phoneProvider.selectedIndex].value);
						//only when it is sent successfully, we will check if we still want to show the message box
						if (document.sendForm.doNotShowMsg.checked) {
							this.checkShowBox(true);
						}                    
						this.showMessage(this.CONTROL_ERROR_ID, "");
						this.showConfirmationTitle();
						this.hideContentPopupLayout(true);
						this.startPopUpTimeout();
					} else {
						this.onFailureSendtophoneSubmit(response);
					}
				}        
			} else {
				this.onFailureSendtophoneSubmit(response);
			}        
        } else {
			this.onFailureSendtophoneSubmit(response);
		}

	this.requestActive = false;
    },

    onFailureSendtophoneSubmit: function(response) {
		//this.displayPopupLayout(false);
        this.showError(this.PROCESSING_ERROR);
		//clear request lock up
        this.requestActive = false;
    },

    displayPopupLayout: function (trueFalse) {
		if (this._elementId == undefined) return;
		var sendToPhoneIcon = $(this._elementId);
		var posOffsetTop = sendToPhoneIcon.offsetTop;
		var posOffsetLeft = sendToPhoneIcon.offsetLeft;
		if (sendToPhoneIcon.offsetParent){
			var curleft = sendToPhoneIcon.offsetLeft
			var curtop = sendToPhoneIcon.offsetTop
			while (sendToPhoneIcon = sendToPhoneIcon.offsetParent) {
				curleft += sendToPhoneIcon.offsetLeft
				curtop += sendToPhoneIcon.offsetTop
			}			
			$('sms_container').style.top = curtop + -1 + 'px';
            $('sms_container').style.left = curleft + -1 + 'px';

		} else {
            
			$('sms_container').style.top = posOffsetTop + -1 + 'px';
            $('sms_container').style.left = posOffsetLeft + -1 + 'px';
		}

		this.showInitialTitle();
		if (trueFalse) {
			$('sms_container').style.display = "block";
            
               if ( document.getElementById('cell_link') ) {
                cellLink = document.getElementById('cell_link');
                cellLink.style.backgroundPosition = "0 -17px";
                cellLink.style.color = "#000";
               }
            
            
		} else {
			if (!this.requestActive)	{
				//Clear pop-up message if there is any
				this.clearPopUpMessage(this.CONTROL_ERROR_ID);
				//Clear pop-up time out
				this.stopPopUpTimeOut();
			}
            
            
			$('sms_container').style.display = "none";
            if ( document.getElementById('cell_link') ) {
                cellLink = document.getElementById('cell_link');
                cellLink.style.color = "#FFD306";
                cellLink.style.backgroundPosition = "0 -34px";
               }
            
            
		}
		
		$('sms_container').style.position = "absolute";
    },

    hideContentPopupLayout: function (trueFalse) {
		if (trueFalse) {
			$(this.HIDE_CONTENT_ID).style.display = "none";
		} else {
			$(this.HIDE_CONTENT_ID).style.display = "block";
		}		
    },

	populateSendToPhoneField: function(phoneNumber, providerId) {
		document.sendForm.phoneNumber1.value = "";
		document.sendForm.phoneNumber2.value = "";
		document.sendForm.phoneNumber3.value = "";
		document.sendForm.phoneProvider.options[0].selected=true;
        if (this.validatePhoneNumberdigit(phoneNumber,10)) {
			this.splitPhoneNumberToForm(phoneNumber);
			document.sendForm.phoneNumber.value=phoneNumber;
			if (phoneNumber.length > 1)	{
				var selectedProviderId = providerId;
				for (var idx=0;idx<document.sendForm.phoneProvider.options.length;idx++) {
					if (selectedProviderId==document.sendForm.phoneProvider.options[idx].value) {
					   document.sendForm.phoneProvider.selectedIndex=idx;
					   document.sendForm.phoneProvider.options[idx].selected=true;
					   break;
					}
				}         
			}
		}
	},

	splitPhoneNumberToForm: function(phoneNumber, providerId) {
		if (phoneNumber.length >= 3)	{
			document.sendForm.phoneNumber1.value = phoneNumber.substring(0,3);
			if (phoneNumber.length > 6){
				document.sendForm.phoneNumber2.value = phoneNumber.substring(3,6);
				if (phoneNumber.length <= 10){
					document.sendForm.phoneNumber3.value = phoneNumber.substring(6,phoneNumber.length);
				} 
			}
		}
	},

    checkSendToPhoneField: function () {
        if (document.sendForm.phoneNumber1.value.length < 1 || !this.validatePhoneNumberdigit(document.sendForm.phoneNumber1.value,3)) {
            this.showError(this.MESSAGE_PHONE_ERROR);
            return false;
	    } else if (document.sendForm.phoneNumber2.value.length < 1 || !this.validatePhoneNumberdigit(document.sendForm.phoneNumber2.value,3)) {
            this.showError(this.MESSAGE_PHONE_ERROR);
            return false;
	    } else if (document.sendForm.phoneNumber3.value.length < 1 || !this.validatePhoneNumberdigit(document.sendForm.phoneNumber3.value,4)) {
            this.showError(this.MESSAGE_PHONE_ERROR);
            return false;
        } else if (document.sendForm.phoneProvider.selectedIndex < 1 ) {
            this.showError(this.MESSAGE_CARRIER_ERROR);        
            return false;
        } 
        return true;
    },

	setSendToPhoneCookie: function(phoneNumber, providerId) {
		var encryptedPhoneNumber = this.encrypteStr(phoneNumber);
        this.createCookie(this.COOKIE_NAME_PHONE, encryptedPhoneNumber);
        this.createCookie(this.COOKIE_NAME_PROVIDER_ID, providerId);
        //default set ShowBox to 0 (0: true, 1: false)
        if (this.readCookie(this.COOKIE_NAME_SHOW_BOX) == null) {
            this.createCookie(this.COOKIE_NAME_SHOW_BOX, 0);
        }
	},

	createCookie: function(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
	},

	readCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
	},

    isShowBox: function () {
        var varShow = this.readCookie(this.COOKIE_NAME_SHOW_BOX);
        if ( varShow == null || varShow == 0 ) {
            return true;
        } else {
            return false;
        }
    },

    checkShowBox: function (blnCheck) {
        if (blnCheck) {
            this.createCookie(this.COOKIE_NAME_SHOW_BOX, 1);
        } else {
            this.createCookie(this.COOKIE_NAME_SHOW_BOX, 0);
        }
    },

    getCookiePhone: function () {		
        return this.decrypteStr(this.readCookie(this.COOKIE_NAME_PHONE));
    },

    getCookieProviderId: function () {
        return this.readCookie(this.COOKIE_NAME_PROVIDER_ID);
    },

    isSendToPhoneCookieSet: function () {
        return (this.getCookiePhone() != null && this.getCookieProviderId() != null);
    },

	validatePhoneNumberdigit: function (phoneNumber, length){
		var str = "/^\\d{" + length + "}$/";
        var digitRegex = eval(str); 
        if (phoneNumber == null) return false;
        if (phoneNumber.search(digitRegex) == -1)
            return false;     
    	return true;
    },

	concatenatePhoneNumber: function () {
		document.sendForm.phoneNumber.value = document.sendForm.phoneNumber1.value 
											+ document.sendForm.phoneNumber2.value 
											+ document.sendForm.phoneNumber3.value;
	},

	xorIt: function (strInput, intKey) {
        return strInput;
        /*
		var strResult = "";
		for(i=0;i<strInput.length;i++)
		{
			strResult+=String.fromCharCode(strInput.charCodeAt(i) ^ intKey);
		}
		return strResult;
        */
	},

	xorItEncryption: function (strInput, intKey) {
		var strResult = "";
		var strEach = "";
		for( i = 0; i < strInput.length ; i++ )
		{
			strEach = strInput.charCodeAt(i) ^ intKey;
			if ( strEach.length < 3)
			{
				for ( s = 0; s < 3 - strEach.length ; s++ )
				{
					strEach = "0" + strEach;
				}
			} else {
				//xor key create a result that is longer than length of 3.  This should never happened.
			}
			strResult += strEach;
		}
		return strResult;
	},

	xorItDecryption: function (strPlainNumericText, intKey) {
		var strResult = "";
		var plainTextLength = strPlainNumericText.length / 3;
		var intInput = new Array();
		for( i = 0; i < plainTextLength ; i++ )
		{
			intInput[i] = strPlainNumericText.substr(i*3, 3);
		}
		for ( i = 0; i < intInput.length ; i++ )
		{
			strResult+=String.fromCharCode(intInput[i] ^ intKey);
		}
		return strResult;
	},

	getKey: function () {
		var jsessionId = this.readCookie(this.COOKIE_NAME_JSESSIONID);
		if (jsessionId == undefined || jsessionId == '') {
			jsessionId = document.location;
		}

		var strSessionKey = jsessionId.substring(jsessionId.length - 8);
		var intKey = 0;
		for (var i=0; i < strSessionKey.length ; i++) {
			intKey += strSessionKey.charCodeAt(i);
		}
		
		while (intKey > 900){
			intKey = Math.floor(intKey / 3);
		}
		
		return intKey;
	},

	decrypteStr: function (encryptedString) {
		if (encryptedString == undefined || encryptedString.length < 1) return '';
		var decryptedResult = this.xorItDecryption(decode64(encryptedString), this.getKey());
		//check in case the session id is changed the decryption might not be corrected. Then return "";
		if (decryptedResult.length > 1 && !this.validatePhoneNumberdigit(decryptedResult, decryptedResult.length))	{
			decryptedResult = "";
		}
		return decryptedResult;
	},

	encrypteStr: function (plaintext) {
		if (plaintext == undefined || plaintext.length < 1) return '';
		return encode64(this.xorItEncryption(plaintext, this.getKey()));
	},

	onFailure: function(response) {
        this.requestActive = false;
        this.showError(this.DEFAULT_ERROR);
    },

    onComplete: function(response) {
        document.body.style.cursor = "auto";
	//this.displayProgressWidget(false);
    },
 
    onException: function(ajaxRequestObj, exception) {
        this.requestActive = false;
        errorMsg = "";
		for (i in exception) {
			errorMsg = errorMsg + i + ": " + exception[i] + "  ";	
		}
		alert("onException: " + errorMsg);
		this.showError(this.PROCESSING_ERROR + ": " + errorMsg);
	
    }

};

