function ajaxLoader(url,id) {
  if (document.getElementById) {
  	document.getElementById(id).innerHTML= "<div class='load'><img src='images/loading.gif'/></div>";
  	//document.getElementById(id).innerHTML= "<div class='load'></div>";
	//alert('ok');
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP"): new XMLHttpRequest();
  }
  if (x) {
    x.onreadystatechange = function() {
      if (x.readyState == 4 && x.status == 200) {
        el = document.getElementById(id);
        el.innerHTML = x.responseText;
        //alert(x.responseText);
      }
    }
    x.open("GET", url, true);
    x.send(null);
  }
}

function contentpaginate(pageurl,commandvalue,offsetval) {
		
		//alert(offsetval);
		var query = fleegix.uri.getQuery(pageurl);
		var url_base = fleegix.uri.getBase(pageurl); //portion before the question mark
		query = fleegix.uri.setParam('pager.offset', offsetval, query);
		
		var urlandparams = url_base + "?" + query;
		if (urlandparams.indexOf("/") != -1)
			urlandparams= urlandparams.substr(1);
		//alert(urlandparams);
		window.location.href = urlandparams;
		
		
}

function submitPage(formObj,commandvalue) {
	 try {
	    var pageoffset = document.getElementById("pageroffset");
	    
	    if (pageoffset) {
	    	//document.all("pager.offset").value = 0;
	    	pageoffset.value = 0;
	    }
	    
	    if (formObj.pagenumberclicked)
			formObj.pagenumberclicked.value = "0";
	   
	   	if (formObj.command)
			formObj.command.value=commandvalue;
		//alert(formObj.command.value);
		 
		formObj.submit();
	
	  }
	  catch(Exception) {
	  	alert("in Exception of SubmitPage" + e);
	  }
	 
}

/****************************************************

Fired when the phone is selected first time

*********************************************************/
function OnChangeOfPhone() {
					//var formaction = $('contentform').action;
					//var pos = formaction.indexOf("?");
					//var urltouse;
					//if (pos != -1)
						//urltouse = formaction.substring(0,pos);
					//else
						//urltouse = formaction;
					//alert(urltouse);
					if ($('pageroffset')) $('pageroffset').value=0;
					//var querystring = formaction.substr(pos);
					var selPhoneObj = $('deviceName');
					var selectedindx = selPhoneObj.selectedIndex;
					var selectedval = selPhoneObj[selectedindx].value;
					var selected_deviceName = selPhoneObj[selectedindx].text;
					
					var indx = selectedindx;
					//var deviceSKU= $('phone_opt_'+indx).getAttribute("deviceSKU");
					
					//alert(deviceSKU);
					//var formaction = "apps_home.do" + "?changephone=Y&deviceName="+encodeURIComponent(selectedval);
					var formaction = "apps_home.do?changephone=Y&deviceId="+encodeURIComponent(selectedval)+"&selected_deviceName="+URLEncode(selected_deviceName);
					$('commonForm').deviceName.value=selected_deviceName;
					//var formaction = "apps_home.do" + "?changephone=Y&deviceName="+URLEncode(selectedval);
					//window.location.href = urlandparams;
					$('commonForm').action = formaction;
					submitPage($('commonForm'),'');
					
}

/****************************************************

Fired when the phone is changed

*********************************************************/

function OnChangeOfSelectedPhone() {
					
					if ($('pageroffset')) $('pageroffset').value=0;
					//var querystring = formaction.substr(pos);
					var selPhoneObj = $('deviceName');
					var selectedindx = selPhoneObj.selectedIndex;
					var selectedval = selPhoneObj[selectedindx].value;
					var selected_deviceName = selPhoneObj[selectedindx].text;
					var indx = selectedindx;
					//var deviceSKU= $('phone_opt_'+indx).getAttribute("deviceSKU");
					
					//alert(deviceSKU);
					var pageURL=$F('prevpageurl');
					//pageURL=URLEncode(pageURL);
					//alert(pageURL);
					
					var query = fleegix.uri.getQuery(pageURL);
					var url_base = fleegix.uri.getBase(pageURL); //portion before the question mark
					query = fleegix.uri.setParam('changephone', 'Y', query);
					//query = fleegix.uri.setParam('deviceName', encodeURIComponent(selectedval), query);
					query = fleegix.uri.setParam('deviceId', encodeURIComponent(selectedval), query);
					query = fleegix.uri.setParam('selected_deviceName', encodeURIComponent(selected_deviceName), query);
					
					//After confirmation page , if phone is changed , go to apps_home.do
					if (url_base.indexOf("buystatus") != -1) {
						url_base = "apps_home.do";
						//alert(url_base);
					}
					var urlandparams = url_base + "?" + query;
					if (urlandparams.indexOf("/") != -1)
						urlandparams= urlandparams.substr(1);
					//alert(urlandparams);
					window.location.href = urlandparams;
					//$('commonForm').action = urlandparams;
					//submitPage($('commonForm'),'');
					
}

function URLEncode(decodedstr)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var plaintext = decodedstr;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
	//document.URLForm.F2.value = encoded;
	//return false;
}

function URLDecode(encodedstr)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   //var encoded = document.URLForm.F2.value;
   var encoded = encodedstr;
   
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
	return plaintext;
   //document.URLForm.F1.value = plaintext;
   //return false;
}

function getItemDetails(itemType,itemId,maturity_flag,frombutton) {

	//alert(itemType);
	//var src = window.event.srcElement; //IE
	//if (!src) 
		//src = window.event.target;
	//alert(src.tagName);
	$('itemId').value=itemId;
	//$('itemtype').value=itemType;
	var mat_flag = "";
	if (isEmptyStr(maturity_flag) || maturity_flag == 'undefined')
		maturityFlag = "";
	else
		mat_flag = maturity_flag;
	//$('commonForm').action='content_details.do?maturity_flag='+mat_flag;
	if (frombutton == 'buying_instructions')
		$('commonForm').action='content_details.do?click=buying_instructions';
	else
		$('commonForm').action='content_details.do';
	submitPage($('commonForm'),'');

}


// The function will be used to redirect request for 'help' & 'terms & conditions' navigation.
function menuRedirect(frombutton) {
	
		if (frombutton == 'help')
			$('commonForm').action='content_help.do';
		else
			$('commonForm').action='content_details.do';
		submitPage($('commonForm'),'');

}



function sendtoPhoneWithBango() {

	//Validate Phone Number
	////validate that the phone number starts with 07 and is either 11 or 12 digits. When sending the number to Bango replace 0 with 44.
	var phone_no = $F('phoneNumber');
	//var regExp = /^07\\d{9}$|^44\\d{10}$'/;
	//alert(phone_no);
	var match = /^07\d{9}$|^44\d{10}$/.test(phone_no);
	//alert(match);
	if (!match) {
		alert('Phone Number must start with 07 and should be either 11 or 12 digits');
		return false;
	}

	$('commonForm').action='content_sendtophone.do';
	submitPage($('commonForm'),'');


}

function buywithCreditCard() {

	//Get all elememts under ul tag with id paymentType02 which are input fields
	var allelements = $$('ul#paymentType02 input');
	for(var i=0; i<allelements.length; i++){
		var fname = allelements[i].id;
		var fvalue = allelements[i].value;
		if (fname != 'address2' && fname != 'city' && fname != 'state') {
			if (isEmptyStr(fvalue)) {
				alert(fname + ' cannot be empty');
				return false;
			}
		}
	}
	
	//Validate Phone Number
	////validate that the phone number starts with 07 and is either 11 or 12 digits. When sending the number to Bango replace 0 with 44.
	var phone_no = $F('cc_phoneNumber');
	//var regExp = /^07\\d{9}$|^44\\d{10}$'/;
	//alert(phone_no);
	var match = /^07\d{9}$|^44\d{10}$/.test(phone_no);
	//alert(match);
	if (!match) {
		alert('Phone Number must start with 07 and should be either 11 or 12 digits');
		return false;
	}
	
	var window_url = window.location.href;
	var url_base = fleegix.uri.getBase(window_url);
	https_url = url_base.replace("http", "https");
	https_url = https_url.replace("content_details", "content_creditcardpurchase");
	//alert(https_url);
	
	//https_url = https_url.replace("https", "http"); //just for dev
	$('commonForm').action = https_url;
	$('commonForm').submit();

}

/******************************************************

Validating a credit Card
http://www.evolt.org/article/rating/17/24700/
Check that only numbers or spaces are given in the credit card number &#8212; not letters or other characters.
Check that, for the given card type, the number of digits given is valid and the prefix to the number is valid.
se the Luhn formula to check the validity of the entered credit card number. This is a special algorithm that can be applied to most credit card numbers to check that the number would be valid
All three are done here

************************************************************/

//Validate.prototype.isValidCreditCardNumber = function(cardNumber, cardType)
function(cardNumber, cardType)
{
  return true;
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
        prefixRegExp = /^$/;
        //alert("Card type not found");
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}

