//Event.observe(window, 'load', page_loaded, false); 
//moved definition to script.jsp within javascript to avoid errors pop up

/*function page_loaded(evt) {
  if ($('tabs'))
  	Event.observe('tabs', 'click', tab_clicked,false);
  	
  //if ($('ul_alldevices'))
  	//Event.observe('ul_alldevices', 'click', device_clicked,false);  
}*/


function recommend(itemId,contentType) {
	tb_show(null, 'popup_recommend.jsp?itemId='+itemId+'&contentType='+contentType+'&KeepThis=true&TB_iframe=true&width=497&height=214', null);
}



//called when tabs is clicked on details page
function tab_clicked(evt){
	//alert('in tab clicked event');
	var child = Event.element(evt);
	//alert(child.id);
	if (Element.hasClassName(child,"hl")) {
		return;
	}
	else {
		hlMe(child);
		if (child.id == 'details_li1') {
			Element.update('tabsContent',$('tabprices').innerHTML);
			
			//Make the price model checked
			var no_of_price_models = $('ul_prices').getAttribute('price_model_length');
			if (no_of_price_models == 1) {
				//alert('here');
				hlMe($('price1'));
				price_clicked($('price1'));
				$('priceInput1').checked = true;
			}
		}
		if (child.id == 'details_li2') {
			var device_display_name = $(child.id).getAttribute("device_display_name");
			//alert(device_display_name);
			ajaxLoader('tell_friend.do?device_display_name='+device_display_name,'tabsContent');
		}
		else if (child.id == 'details_li3') {
			var rating = $(child.id).getAttribute("itemrating");
			//alert(rating);
			ajaxLoader('rate_it.do?rating'+rating,'tabsContent');	
		}
	}
	Event.stop(evt);
}

/********************************************************************

 Function for send to Phone and Place order

*************************************************************************/
function sendtoPhone() {

	
	var phone_no=$F('sendtophone_ptn');
	//alert(phone_no);
	//By default the class attaches an event observer to the form's onsubmit event. 
	//If you prefer to do the form submit via javascript yourself you can still validate the form like this:
	var valid = new Validation('commonForm', {onSubmit:false,stopOnFirst:true,useTitles : true});
	
    var result = valid.validate();
    //alert(result);
    if (!result)
    	return;
    
    //paymentType_value is hardcoded to sendtophone as credit card is now completely on their side
	var  paymentType_value = 'sendtophone';
	
	//
    /*var paymentType = $('commonForm').getInputs('radio', 'paymentType');
    for (i=0; i<paymentType.length; i++) {
    	if (paymentType[i].checked)
    		 paymentType_value = paymentType[i].value;
    }*/
    //alert(paymentType_value);
    
    /*if (paymentType_value == 'creditcard') {	
    
	    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_viewCart", "content_sendtophone");
		alert(https_url);
		
		https_url = https_url.replace("https", "http"); //just for dev
		alert(https_url);
		$('commonForm').action = https_url;
		$('commonForm').submit();
		
		return;
	}*/
    	
	//else for send to phone , no need to call https
	//$('commonForm').action='content.do?itemId='+itemid+'&itemTypeId='+itemTypeId+'&devicedisplayname='+devicedisplayname+'&command=sendtophone&phone_no='+phone_no;
	if (paymentType_value == 'sendtophone') {
		$('commonForm').action='content_sendtophone.do?paymentType=sendtophone&phone_no='+phone_no;
		$('commonForm').submit();
	}
	//alert($('commonForm').action);

}



/********************************************************************

 Function for Paying by Credit card

*************************************************************************/
function paybyCreditCard() {

	
	var phone_no=$F('sendtophone_ptn');
	//alert(phone_no);
	//By default the class attaches an event observer to the form's onsubmit event. 
	//If you prefer to do the form submit via javascript yourself you can still validate the form like this:
	var valid = new Validation('commonForm', {onSubmit:false,stopOnFirst:true,useTitles : true});
	
    var result = valid.validate();
    //alert(result);
    if (!result)
    	return;
    	
    
    	
    //Check if there are any subscription items for CC .. no subscription items for CC purchase
    var cart_count = $F('txtCartItemcount');
    if (cart_count < 1) {
    
    	var msg = "<font color=red>Please add items to the cart before placing an order.</font>";
    	Element.update('validate_cc_msg',msg);
    	return;
    }
    
    for(i=1;i<=cart_count;i++) {
    	var cart_item = $F('txtCartItem'+i);
    	var decoded_cart_item = URLDecode(cart_item);
    	//alert(decoded_cart_item);
    	
    	//if (decoded_cart_item.indexOf('"SUBSCRIPTION_FLAG":1') != -1) {
    	if (decoded_cart_item.indexOf('"BUY_DISPLAY_TEXT":"Subscription"') != -1) {
    	
    		//var startindex = decoded_cart_item.indexOf('"DEVICE_DISPLAY_NAME":') + 22 ;
    		//var endindex = decoded_cart_item.indexOf('"DOMAIN_URL":') - 1;
    		
    		//alert(startindex);
    		//alert(endindex);
    		//var itemName = decoded_cart_item.substring(startindex,endindex);
    		var itemName = $F('txtCartItemName'+i);
    		//alert(itemName);
    	
    		if ($('validate_cc_msg')) {
    			//alert(decoded_cart_item);
    			//var msg = "<font color=red>Subscription item "+itemName+" is not allowed for Credit Card Purchase.Please remove subscription items from cart</font>";
    			var msg = "<font color=red>"+itemName+": Este es un tema que la suscripción no está permitida para la Tarjeta de Crédito Purchase.Please eliminar este elemento de la cesta de la compra para continuar.</font>";
    			Element.update('validate_cc_msg',msg);
    			
    		}
    		return;
    	}
    	
    }
    
    
    //Validate spending limit
 
 	var validate_error = 0;
		var opt = {
				    // Use GET
				    method: 'post',asynchronous:true,
				    postBody: 'phone_no='+phone_no,
				    //postBody: params.substr(1), 
				    onCreate: function(t) {
				    	//alert("making call");
				    	$('validate_cc_msg').innerHTML = '<font color=red>Validating Spending Limit. Please wait ...</font>';
				    },
				     // Handle successful response
				    onSuccess: function(t) {
				    	var resp = t.responseText; 
				    	
				    	if (resp == 'success') {
				    	
				    		$('commonForm').action='content_paybycreditcard.do?paymentType=creditcard&phone_no='+phone_no;
							$('commonForm').submit();
				    	
				    	}
				    	
				    	if (resp != 'success') {
				    		//alert(resp);
				    		$('validate_cc_msg').innerHTML = '<font color=red>'+resp+'</font>';
				    		return;
				    		
				    	}
				    },
				   
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    }
				}
			
		new Ajax.Request('content_validate_before_creditcard.do', opt);
		
	// End of Validate spending limit
   
    
	
	//$('commonForm').action='content_paybycreditcard.do?paymentType=creditcard&phone_no='+phone_no;
	//$('commonForm').submit();
	
	

}


/********************************************************************

 Function for Contact Us form

*************************************************************************/
function contactUs() {

	
	//alert(phone_no);
	//By default the class attaches an event observer to the form's onsubmit event. 
	//If you prefer to do the form submit via javascript yourself you can still validate the form like this:
	var valid = new Validation('commonForm', {onSubmit:false,stopOnFirst:true,useTitles : true});
	
    var result = valid.validate();
    //alert(result);
    if (!result)
    	return;
    	
    //Send e-mail to contacto.shotsonline@nextel.com.mx
    var name= $F('contact_name');
    var email= $F('contact_emal');
    var name= $F('contact_name');
    var areacode1= $F('contact_arcode1');
    var ptn1= $F('contact_ptn1');
    var ext1= $F('contact_ext1');
    var areacode2= $F('contact_arcode2');
    var ptn2= $F('contact_ptn2');
    var ext2= $F('contact_ext2');
    var comments= $F('contact_comments');
    
    var ContactParams = new Array("keys","values");		
	ContactParams["keys"] = Array	("sendmail","name","email","areacode1","ptn1","ext1","areacode2","ptn2","ext2","comments");
	ContactParams["values"] = Array	("Y",name,email,areacode1,ptn1,ext1,areacode2,ptn2,ext2,comments);
	var url_1 = "content_contactus.do"+createParams(ContactParams);
			
	var params = createParams(ContactParams);
    
		var opt = {
				    // Use GET
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params.substr(1), 
				    onCreate: function(t) {
				    	$('contact_statusmsg').innerHTML = "Sending Message . Please wait ..";
				    	//if (sync_var_bucketII == 0)
				       		//$('buckets_containerII').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loading2.gif) center center no-repeat;"></div>';
				    },
				     // Handle successful response
				    onSuccess: function(t) {
				    	var resp = t.responseText; 
				    	//alert(resp);
				    	//if (resp == "-1")
				    		//$('contact_statusmsg').innerHTML = "Error al enviar mensaje.";
				    	//else
				        	$('mmboxbg').innerHTML = resp; //bug 10338
				        	//$('contact_statusmsg').innerHTML = "Mensaje enviado.";
				        //else
				        	//$('contact_statusmsg').innerHTML = "Error al enviar mensaje.";
				        	//$('contact_statusmsg').innerHTML = "Error in sending message";
				        
				    },
				   
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    }
				}
			
		new Ajax.Request('content_contactus.do', opt);
    
}


/*******Rating item ********************/
function rateit(obj,value){
	
	//alert(obj.id);
	//alert(value);
	$('commonForm').action='content.do?command=rateitem&rating='+value;
	
}

function submitrating(){
	
	var rating;
	
	var radio_btn = $('commonForm').rateIt;
	for (var i=0; i<radio_btn.length; i++)  { 
		if (radio_btn[i].checked)  {
			rating = radio_btn[i].value
		} 
	} 
	
	if (rating == 0 || rating == 'undefined')
		rating = 5;
	//alert(rating);
	$('commonForm').action='content.do?command=rateitem&rating='+rating;
	$('commonForm').submit();
	//$('commonForm').action='content.do?command=rateitem&rating='+value;
	
}

//function addOption( form, elementName, text, value)
function addOption( elementName, text, value)
    {
        //var myElement = form[elementName];
        var myElement = $(elementName);
        var insertAt = myElement.options.length;
    for ( j = 0; j < insertAt; j++ )
    {
        if ( myElement.options[j].value == value )
        return;
    }
        var newOption = new Option (text,value);
        myElement.options.length = insertAt + 1;
       /**
            We need to add the item at the beginning of the list.
            So, we need to move all options 1 index down in this loop.
            After this, we add the new option at the beginning
            ie. 0 index.
        */
        /*for ( j = insertAt; j > 0; j-- )
        {
            myElement.options[j].text = myElement.options[j-1].text;

            myElement.options[j].text = myElement.options[j-1].text;
            myElement.options[j].value = myElement.options[j-1].value;
        }

        myElement.options[0] = newOption;
        myElement.options[0].selected = true;*/
        // Below is for adding it at the end.
        myElement.options[insertAt] = newOption;
        myElement.options[insertAt].selected = true;
        return;
    }
    
    //function removeOption(form, elementName, value)
    function removeOption(elementName, value)
    {
        //var myElement = form[elementName];
        var myElement = $(elementName);
    var myElementLength = myElement.options.length;
    for ( k = 0; k < myElement.length; k++)
        {
        if ( myElement.options[k].value == value )
        {
        myElement.options[k] = null;
        //if (k > 0)
        	//myElement.options[k-1].selected = true;
        return;
        }        
    }
    }
    
     function checkOptionExists(elementName, value)
    {
        //var myElement = form[elementName];
        var myElement = $(elementName);
    var myElementLength = myElement.options.length;
    for ( k = 0; k < myElement.length; k++)
        {
        if ( myElement.options[k].value == value )
        {
        	return true;
        }        
    }
    	return false;
    }


function onChangeOfPhone(deviceId,deviceName,deviceImage) {

	//alert('here');
	//alert(top.document.forms['commonForm'].action);
	top.document.forms['commonForm'].action='content_setDeviceinSession.do?deviceid='+deviceId+'&devicename='+deviceName+'&deviceImage='+deviceImage;
	top.document.forms['commonForm'].submit();

}

function sendEmail() {

	var toemail = $F('toemail');
	var subject = $F('emailsubject');
	var message = $F('emailBody');
											
	//alert(phone_no);
	
	if (isEmptyStr(toemail) || !isEmail (toemail)) {
		alert('Please enter a valid email address');
		return false;
	}
	//$('commonForm').action='content.do?itemId='+itemid+'&itemTypeId='+itemTypeId+'&devicedisplayname='+devicedisplayname+'&command=sendtophone&phone_no='+phone_no;
	$('commonForm').action='content.do?command=sendemail&sendto='+toemail+'&subject='+subject+'&message='+message;
	$('commonForm').submit();
	//alert($('commonForm').action);

}

//called when device is clicked to select a device
function device_clicked(evt){
	//alert('in tab clicked event');
	var child = Event.element(evt);
	//alert(child.id);
	var deviceid = child.id.substr(3);
	var devicename = $(child.id).getAttribute("devicename");
	
	if (isEmptyStr(deviceid))
		return;
	//alert(deviceid);
	
		var params = "command=setdeviceinsession&deviceid="+deviceid+"&devicename="+devicename;
		var opt = {
				    // Use GET
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params, 
				    onCreate: function(t) {
				    	//if (sync_var_bucketII == 0)
				       		//$('buckets_containerII').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loading2.gif) center center no-repeat;"></div>';
				    },
				     // Handle successful response
				    onSuccess: function(t) {
				    	//var resp = t.responseText; //getting the disbaled array from here
				        //$('ul_alldevices').innerHTML = resp;
				        
				    },
				   
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    }
				}
			
		new Ajax.Request('content.do', opt);
		toggle_element('selectPhone');

	Event.stop(evt);
	
	//alert($('prevpageurl').value);
	if ($('prevpageurl')) {
		var url = $('prevpageurl').value;
		if (!isEmptyStr(url))
			window.location.href= url.substr(1);
	}
	
}



function OnKeyPressOfGlobalSearch() {

		if ((window.event.keyCode == 13) && ((window.event.srcElement.name == "keysearchfield"))) {
			//alert('here in globalsearch');
			transitSearch('',$('keysearchfield').value);
		}
}


/***********************************************************
Pauses for a few seconds and thenexecutes the next line
*****************************************************************/
function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
}

function SearchByArtist() {

	var index = $('AllArtistName').selectedIndex;
  	var artist_value = $('AllArtistName').options[index].value;
  	
	var url = "content_globalsearchbyartists.do?itemtype=rt&artistvalue="+artist_value;
	//alert(url);
	window.location.href= url;
}



/*****************************************/

function ajaxLoader(url,id) {
  //alert(url);
  if (document.getElementById) {
  	$(id).innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></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 createParams(Params) {
	var querystr = "?";
	for(i=0;i<Params["keys"].length;i++) {
		querystr += Params["keys"][i]+"="+encodeURIComponent(Params["values"][i])+"&"; //or encodeURI
	}
	return querystr;
}



//Function fired when the Search Button is clicked
function transitSearch(itemType,searchfield){

		
		if (isEmptyStr(searchfield) || searchfield.length < 3) {
			searchfield = '';
			alert('SearchField should have at least 3 characters');
			return;
		}
		
		var url = 'globalsearch.do?searchfield='+searchfield+'&itemtype='+itemType;
		window.location.href = url;
		
		/*$('commonForm').action='globalsearch.do?searchfield='+searchfield;
		if (!isEmptyStr(itemType))
			$('commonForm').action=
		submitPage(document.forms['commonForm'],'');*/
}



function submitPage(formObj,actionpath) {

	//alert('HERE');
	 try {
	   // var pageoffset = document.all("pager.offset");
	 
	    var pageoffset = $('content_pageroffset');
	    
	    if (pageoffset) {
	    	//document.all("pager.offset").value = 0;
	    	pageoffset.value = 0;
	    }
	    
	    if (formObj.pagenumberclicked)
			formObj.pagenumberclicked.value = "0";
	   
	   	
		
		if (!isEmptyStr(actionpath)) {
			//alert("specified action for form");
			formObj.action = actionpath;
		}
			
		formObj.submit();
	
	  }
	  catch(Exception) {
	  	alert("in Exception of SubmitPage");
	  }
	 
}



function previewItem(contentType, preview_url) {
	ajaxLoader('content_getCart_Preview.do?itemtype='+contentType+'&preview_url='+preview_url,'displayPreview');
}

//function contentpaginate(formname,act,commandvalue,offsetval) {
function searchpaginate(pageurl,commandvalue,offsetval) {
		//var formObj = document.forms['ringtoneForm'];
		//var formObj = document.all(formname);
		//alert(formname);
		//alert(pageurl);
		//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;
		
		
}

//contentpaginate(${param.itemtype},'${param.paginate_content}',<c:out value="${pageoffsetvalue}"/>,${itemsize })
function contentpaginate(itemtype,paginate_content,offsetval,itemsize) {
		//var formObj = document.forms['ringtoneForm'];
		//var formObj = document.all(formname);
		//alert(formname);
		//alert(itemsize);
		//alert(offsetval);
		
		var Params = new Array("keys","values");		
		Params["keys"] = Array	("itemtype","paginate_content","pager.offset","itemsize");
		Params["values"] = Array	(itemtype,paginate_content,offsetval,itemsize);
		var div_id = '';
		
		var paginate_params = createParams(Params);
		//alert(paginate_params);
		
		switch(paginate_content) {
			  case 'rt_new':
			  		
		  		//var urlandparams = "ringtones.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
				//ajaxLoader(urlandparams,'buckets_containerII');
				var url = "home_paginateLists.do";
				div_id = 'rt_whatsnew';
				break;
			
			case 'rt_top':
				var url = "home_paginateLists.do";
				div_id = 'rt_top';
				break;
				
			case 'games_new':
			  		
		  		//var urlandparams = "ringtones.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
				//ajaxLoader(urlandparams,'buckets_containerII');
				var url = "home_paginateLists.do";
				div_id = 'games_whatsnew';
				break;
			
			case 'games_top':
				var url = "home_paginateLists.do";
				div_id = 'games_top';
				break;
				
			case 'wp_new':
			  		
		  		//var urlandparams = "ringtones.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
				//ajaxLoader(urlandparams,'buckets_containerII');
				var url = "home_paginateLists.do";
				div_id = 'wp_whatsnew';
				break;
			
			case 'wp_top':
				var url = "home_paginateLists.do";
				div_id = 'wp_top';
				break;
				
			case 'apps_new':
			  		
		  		//var urlandparams = "ringtones.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
				//ajaxLoader(urlandparams,'buckets_containerII');
				var url = "home_paginateLists.do";
				div_id = 'apps_whatsnew';
				break;
			
			case 'apps_top':
				var url = "home_paginateLists.do";
				div_id = 'apps_top';
				break;
			
			case 'searchbycategory':
				var pageurl = $('prevpageurl').value;
				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);
				paginate_params = "?"+query;
				//alert(paginate_params);
				
				//var paginate_params = url_base + "?" + query;
				//if (paginate_params.indexOf("/") != -1)
					//paginate_params = urlandparams.substr(1);
				//alert(urlandparams);
				//window.location.href = urlandparams;
			
				var url = pageurl;
				div_id = 'displayContent';
				break;
				
			case 'promodetails':
				var pageurl = $('prevpageurl').value;
				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);
				query = fleegix.uri.setParam('menu', 'promo', query);
				paginate_params = "?"+query;
				//alert(paginate_params);
				
				var urlandparams = "/nextelmx"+url_base + "?" + query;
				//if (paginate_params.indexOf("/") != -1)
					//paginate_params = urlandparams.substr(1);
				//alert(urlandparams);
				window.location.href = urlandparams;
			
				//var url = pageurl;
				//div_id = 'displayContent';
				break;
		}
		
			var params_opt = {
					    // Use POST
					    method: 'post',asynchronous:true,
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: paginate_params.substr(1), 
					    onCreate: function() {
					    	
					    		$(div_id).innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
				       			//$('buckets_containerIII').innerHTML = "<div class='load'></div>";
				       			
				       		
				    	},
					     // Handle successful response
					    onSuccess: function(t) {
					    	
					    	var resp = t.responseText; //getting the disbaled array from here
					        //alert(resp);
					        $(div_id).innerHTML = resp;
					        
					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
					    
					    		if (div_id == 'displayContent') { //Paginations for items by category
						    		//Show the details of the first Item
							    	if ($('line_item_1')) {
							    		var itemId = $('line_item_1').getAttribute("itemId");
							    		var maturity_flag = $('line_item_1').getAttribute("maturity_flag");
							    		var itemType = $('line_item_1').getAttribute("itemType");
							    		//alert(itemId);
							    		getItemDetails(itemType,itemId,maturity_flag,'') ;
							    	}
							    }
					       
					    }
					}
					
		new Ajax.Request(url, params_opt);
					
		/*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 toggle_element(id){

	var el = $(id);
	if (Element.hasClassName(el,"hide")) {
		var elem = Element.removeClassName(el, "hide");
	}
	else {
		var elem = Element.addClassName(el, "hide");
	}
	
	return elem;
	

	/*var el = document.getElementById(id);
	if (el.className == "hide") {
		el.className = "";
	} else {
		el.className = "hide";
	}	*/		
}



function getAllDevices() {

		var params = "command=getalldevices";
		var opt = {
				    // Use GET
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params, 
				    onCreate: function(t) {
				       		$('ul_alldevices').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loading2.gif) center center no-repeat;"></div>';
				    },
				     // Handle successful response
				    onSuccess: function(t) {
				    	var resp = t.responseText; //getting the disbaled array from here
				        //alert(resp);
				        $('ul_alldevices').innerHTML = resp;
				        
				    },
				   
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    }
				}
			
		new Ajax.Request('content_alldevices.do', opt);

}

/*********************************************
 Fired for Ringtone Sort Order

************************************************************/

function OnChangeofSort(obj) {

    var indx = obj.selectedIndex;
    var sortValue = obj.options[indx].value;
   // alert(sortValue);

	var pageurl = $('prevpageurl').value;
	//alert(pageurl);
	var query = fleegix.uri.getQuery(pageurl);
	var url_base = fleegix.uri.getBase(pageurl); //portion before the question mark
	query = fleegix.uri.setParam('pager.offset', '0', query);
	query = fleegix.uri.setParam('sortby', sortValue, query);
	paginate_params = "?"+query;
	//alert(url_base);
	//alert(query);
	
	var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: query, //to get rid of ?, 
			    onCreate: function(t) {
			       		$('displayContent').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        $('displayContent').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Show the details of the first Item
			    	if ($('line_item_1')) {
			    		var itemId = $('line_item_1').getAttribute("itemId");
			    		var maturity_flag = $('line_item_1').getAttribute("maturity_flag");
			    		var itemType = $('line_item_1').getAttribute("itemType");
			    		//alert(itemId);
			    		getItemDetails(itemType,itemId,maturity_flag,'') ;
			    	}
			    }
	
			}
		
		new Ajax.Request(url_base, opt_content);
}

/*********************************************************

	Function called when categories are clicked
************************************************************/
function searchbycategory(el,categoryValue,itemType,categoryText){

	for( var i = 0; $('categoryListings').childNodes[i]; i++ ){
		$('categoryListings').childNodes[i].className = '';
	}

	var deviceId = $('txtdeviceId').value;
	if (isEmptyStr(deviceId))
		deviceId = '0';
		
	el.parentNode.className = 'hl';
	
	$('displayCategory').className = 'half';
	$('displayPreview').className = 'half';
	
	//var params = "command=getalldevices";
	
	var ContentParams = new Array("keys","values");		
	ContentParams["keys"] = Array	("deviceid","categorynodeId","itemtype","categorytext");
	ContentParams["values"] = Array	(deviceId,categoryValue,itemType,categoryText);
	var url_1 = "content_searchbycategory.do"+createParams(ContentParams);
	
	//var urlandparams = url_base + "?" + query;
	//alert("Final URL:"+url_1);
	$('prevpageurl').value = url_1;
 		
	var contentparams = createParams(ContentParams);
	var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: contentparams.substr(1), //to get rid of ?, 
			    onCreate: function(t) {
			       		$('displayContent').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        $('displayContent').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Show the details of the first Item
			    	if ($('line_item_1')) {
			    		var itemId = $('line_item_1').getAttribute("itemId");
			    		var maturity_flag = $('line_item_1').getAttribute("maturity_flag");
			    		var itemType = $('line_item_1').getAttribute("itemType");
			    		//alert(itemId);
			    		getItemDetails(itemType,itemId,maturity_flag,'') ;
			    	}
			    }
	
			}
		
	new Ajax.Request('content_searchbycategory.do', opt_content);
	//ajaxLoader('WEB-INF/jsp/'+contentType+'_preview.jsp','displayPreview');
	
	//ajaxLoader('WEB-INF/jsp/'+contentType+'_listings.jsp','displayContent');

}

/*******************************************************

	For Getting item details at item level
	BundleId is not used for the time being, so pass that as an empty parameter

***********************************/
function getItemDetails(itemType,itemId,maturity_flag,bundleId) {

	if (!$("contentDetails")) {
		alert("Error in getting item details");
		//location.href = contentType + '_details.jsp?id='+contentId+'&u=' + loginStatus + '&p=' + phoneModel + '&pn=' + phoneModelName + '&menu=' + contentType;
		return;
	}

	
	$("PreviewLayer").style.display="none";
	$('displayCategory').className = 'half';
	$('displayPreview').className = 'half';
	
	var mat_flag = "";
	if (isEmptyStr(maturity_flag) || maturity_flag == 'undefined')
		mat_flag = "";
	else
		mat_flag = maturity_flag;
	
	var DetailParams = new Array("keys","values");		
	DetailParams["keys"] = Array	("deviceid","itemId","itemtype","maturity_flag");
	DetailParams["values"] = Array	(deviceId,itemId,itemType,mat_flag);
	var url_1 = "content_item_details.do"+createParams(DetailParams);
	
	//var urlandparams = url_base + "?" + query;
	//alert("Final URL:"+urlandparams);
	$('txtcontentDetailsurl').value = url_1;
	
	var deviceId = $('txtdeviceId').value;
	//if (isEmptyStr(deviceId))
		//deviceId = '0';
 		
	var detail_params = createParams(DetailParams);
	var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: detail_params.substr(1), //to get rid of ?, 
			    onCreate: function(t) {
			       		$('contentDetails').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        $('contentDetails').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Refresh the details review section
			    	if ($('item_details_preview')) {
			    		//Refresh the details review section
			    		Element.update('displayPreview',$('item_details_preview').innerHTML);
			    	}
			    	//alert($('displayPreview').innerHTML);
			    }
	
			}
		
	new Ajax.Request('content_item_details.do', opt_content);

	/*if (contentType == 'bundle'){
		ajaxLoader('WEB-INF/jsp/bundle_details_content.jsp','contentDetails');
		ajaxLoader('WEB-INF/jsp/bundle_preview.jsp','displayPreview');
	}
	else {
		ajaxLoader('WEB-INF/jsp/'+contentType+'_details_content.jsp?id='+contentId,'contentDetails');
		ajaxLoader('WEB-INF/jsp/'+contentType+'_preview.jsp?id='+contentId,'displayPreview');
	}*/
	

}

/*******************************************************

	For Getting item details at itemtype level ..also fetches categories etc
	BundleId is not used for the time being, so pass that as an empty parameter

***********************************/
function getDetails(itemType,itemId,maturity_flag,bundle_flag) {

	
	var mat_flag = "";
	if (isEmptyStr(maturity_flag) || maturity_flag == 'undefined')
		mat_flag = "";
	else
		mat_flag = maturity_flag;
	
	var DetailParams = new Array("keys","values");		
	DetailParams["keys"] = Array	("itemId","itemtype","maturity_flag","bundle_flag","menu");
	DetailParams["values"] = Array	(itemId,itemType,mat_flag,bundle_flag,itemType);
	var url_1 = "content_details.do"+createParams(DetailParams);
	//alert(url_1);
	
	window.location.href = url_1;
 		
	/*var detail_params = createParams(DetailParams);
	var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: detail_params.substr(1), //to get rid of ?, 
			    onCreate: function(t) {
			       		$('contentDetails').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        $('contentDetails').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Refresh the details review section
			    	if ($('item_details_preview')) {
			    		//Refresh the details review section
			    		Element.update('displayPreview',$('item_details_preview').innerHTML);
			    	}
			    	//alert($('item_details_preview').innerHTML);
			    }
	
			}
		
	new Ajax.Request('content_item_details.do', opt_content);*/



}

/*******************************************************

	For Getting promotion details

***********************************/
function getPromoDetails(promotionId,promotitle,promoDesc) {

	var DetailParams = new Array("keys","values");		
	DetailParams["keys"] = Array	("promotionId","promotitle","promodesc");
	DetailParams["values"] = Array	(promotionId,URLEncode(promotitle),URLEncode(promoDesc));
	var url_1 = "promo_details.do"+createParams(DetailParams);
	//alert(url_1);
	
	window.location.href = url_1;
}

/******************************************************************

Removing Items to Cart
*****************************************************/

function removeItemfromCart(itemId) {

	var DetailParams = new Array("keys","values");		
	DetailParams["keys"] = Array	("itemId");
	DetailParams["values"] = Array	(itemId);
	var url_1 = "content_removeItemFromCart.do"+createParams(DetailParams);
	//alert(url_1);
	
	var detail_params = createParams(DetailParams);
	
	var pageurl = $F('prevpageurl');
	//alert(pageurl);
	
	var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: detail_params.substr(1), //to get rid of ?, 
			    onCreate: function(t) {
			       		
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        //$('contentDetails').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Refresh the details review section
			    	window.location.href = "/nextelmx"+pageurl;
			    	
			    }
	
			}
			
			new Ajax.Request('content_removeItemFromCart.do', opt_content);
			
			


}

/******************************************************************

Adding Items to Cart
*****************************************************/
function addToCart(itemId, deviceId,phoneModelName,showcart) {
	//alert(deviceId);
	
	var phoneModel = "";
	if (isEmptyStr(phoneModelName) || phoneModelName == 'undefined')
		phoneModel = "";
	else
		phoneModel = phoneModelName;
	if (!isInteger (deviceId) || deviceId == 0)
		alert("Por favor, seleccione un dispositivo con el que desea comprar el contenido.");
		//alert("Please select a device you would like to buy content for.");
	else {
	
				var DetailParams = new Array("keys","values");		
				DetailParams["keys"] = Array	("itemId","deviceId","phoneModel","showcart","KeepThis","TB_iframe","width","height");
				DetailParams["values"] = Array	(itemId,deviceId,phoneModel,showcart,"true","true","497","214");
				var url_1 = "content_addItemToCart.do"+createParams(DetailParams);
				//alert(url_1);
			 		
				var detail_params = createParams(DetailParams);
				/*var opt_content = {
			    // Use GET
			    method: 'post',asynchronous:true,
			    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
			    postBody: detail_params.substr(1), //to get rid of ?, 
			    onCreate: function(t) {
			       		$('contentDetails').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loadingAnimation.gif) center center no-repeat;"></div>';
			    },
			     // Handle successful response
			    onSuccess: function(t) {
			    	var resp = t.responseText; 
			        //alert(stripWhitespace(resp));
			        $('contentDetails').innerHTML = resp;
			        //alert($('displayContent').innerHTML);
			        
			    },
			   
			     // On Complete acts as a postfunction
			    onComplete: function(t) {
			    
			    	//Refresh the details review section
			    	if ($('item_details_preview')) {
			    		//Refresh the details review section
			    		Element.update('displayPreview',$('item_details_preview').innerHTML);
			    	}
			    	//alert($('item_details_preview').innerHTML);
			    }
	
			}*/
		
		//new Ajax.Request('content_details.do', opt_content);
		//tb_show(null, 'popup_cart.jsp?productId='+contentId+'?KeepThis=true&TB_iframe=true&width=497&height=214', null);
		tb_show(null,url_1 , null);
	}
}

function viewCart(deviceId, deviceName) {
	//tb_show(null, 'popup_cart.jsp?KeepThis=true&TB_iframe=true&width=499&height=393', null);
	
	//alert('here');
	var phoneModel = "";
	if (isEmptyStr(deviceName) || deviceName == 'undefined') {
		//alert("Please select a device you would like to buy content for.");
		alert("Por favor, seleccione un dispositivo con el que desea comprar el contenido.");
		phoneModel = "";
		return;
	}
	else
		phoneModel = deviceName;
	if (!isInteger (deviceId) || deviceId == 0) {
		//alert("Please select a device you would like to buy content for.");
		alert("Por favor, seleccione un dispositivo con el que desea comprar el contenido.");
		return;
	}
	
	var url = "content_viewCart.do?deviceId="+deviceId+"&deviceName="+deviceName;
	location.href = url;
}



function transitPhone(deviceName,deviceImage,deviceId){
	//var answer=confirm("Your items will be removed from shopping cart if they are not compatible with the phone you have selected.")
	//bug # 10301
	var answer=confirm("Los artículos que se encuentran en el Cart-Shot podrán ser removidos si no son compatibles con el equipo que se ha seleccionado.");
	if(answer)
	{
				
			var DeviceParams = new Array("keys","values");		
			DeviceParams["keys"] = Array	("deviceid","deviceName","deviceImage");
			DeviceParams["values"] = Array	(deviceId,deviceName,deviceImage);
			var url_1 = "content_details.do"+createParams(DeviceParams);
			
			var device_params = createParams(DeviceParams);
			/*var opt_device = {
					    // Use GET
					    method: 'post',asynchronous:true,
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: device_params.substr(1), //to get rid of ?, 
					    onCreate: function(t) {
					       		//$('contentDetails').innerHTML = '<div style="padding:0 0 0 8px; text-align:center !important; width:222px; height:174px;background:url(images/loading2.gif) center center no-repeat;"></div>';
					    },
					     // Handle successful response
					    onSuccess: function(t) {
					    	var resp = t.responseText; 
					        //alert(stripWhitespace(resp));
					        //$('selected_phone_details').innerHTML = resp;
					        //alert($('displayContent').innerHTML);
					        
					        $('txtdeviceId').value = deviceId;
					        
					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
					    
					    	
					    }
			
			}
		
		new Ajax.Request('content_setDeviceinSession.do', opt_device);*/
		toggle_element('selectPhone');
		$('commonForm').action = 'content_setDeviceinSession.do'+device_params;
		$('commonForm').submit();
		//return;
	}
	else
	{
		toggle_element('selectPhone');
	}
}







// -------------------------------------------------------------------
// tabNext(input_object)
//   Pass an form input object. Will focus() the next field in the form
//   after the passed element.
//   a) Will not focus to hidden or disabled fields
//   b) If end of form is reached, it will loop to beginning
//   c) If it loops through and reaches the original field again without
//      finding a valid field to focus, it stops
// -------------------------------------------------------------------
function tabNext(obj) {

	/*
	  in case CSS is not your forte, the expression below says
	  'find all the INPUT elements that are inside 
	  elements with class=field that are inside a DIV
	  with id equal to loginForm.'
	  
	  var f = $$('div#loginForm .field input');
	var s = '';
	for(var i=0; i<f.length; i++){
		s += f[i].value + '/';
	}
	alert(s); // shows: "joedoe1/secret/"
	
	where html is like
	  
	  <div id='loginForm'>
	<div class='field'>
		<span class='fieldName'>User name:</span>
		<input type='text' id='txtName' value='joedoe1'/>
	</div>
	<div class='field'>
		<span class='fieldName'>Password:</span>
		<input type='password' id='txtPass' value='secret' />
	</div>
	<input type='submit' value='login' />
</div> 
	*/
	
	//Get all elememts under div tag detail_phone_number
	//var allelements = $$('div#device_login input');
	var allelements = $$('div#device input');
	var s = '';
	/*for(var i=0; i<allelements.length; i++){
		s += allelements[i].id + '/';
	}
	alert(s);*/ // shows: "joedoe1/secret/"
	
	//alert('here');
	if (navigator.platform.toUpperCase().indexOf("SUNOS") != -1) {
		obj.blur(); return; // Sun's onFocus() is messed up
		}
	//var theform = obj.form;
	//alert(theform.name);
	var tabtonext = false;
	var i = getElementIndex(obj);
	//alert(i);
	var j=i+1;
	if (j >= allelements.length) { j=0; }
	if (i == -1) { return; }
	while (j != i) {
		if ((allelements[i].id!="area_code") && (allelements[i].id!="first_three"))
			return;
		if ((allelements[i].id =="area_code")) {
			var len = allelements[i].value.length;
			//alert(len);
			if (len == 3) {
				tabtonext = true;
				//alert("entered");
			}
		}
		if ((allelements[i].id =="first_three")) {
			var len = allelements[i].value.length;
			if (len == 3)
				tabtonext = true;
		}
		//alert(tabtonext);
		if ((allelements[j].type!="hidden") && 
		    (allelements[j].id != allelements[i].id) && 
			(!allelements[j].disabled) && tabtonext) {
			allelements[j].focus();
			break;
			}
		j++;
		if (j >= allelements.length) { j=0; }
		}
}

// -------------------------------------------------------------------
// tabNext(input_object)
//   Pass an form input object. Will focus() the next field in the form
//   after the passed element.
//   a) Will not focus to hidden or disabled fields
//   b) If end of form is reached, it will loop to beginning
//   c) If it loops through and reaches the original field again without
//      finding a valid field to focus, it stops
// -------------------------------------------------------------------
function tabNextSendToPhone(obj) {

	
	var allelements = $$('div#sendtoFriend input');
	var s = '';
	/*for(var i=0; i<allelements.length; i++){
		s += allelements[i].id + '/';
	}
	alert(s);*/ // shows: "joedoe1/secret/"
	
	//alert('here');
	if (navigator.platform.toUpperCase().indexOf("SUNOS") != -1) {
		obj.blur(); return; // Sun's onFocus() is messed up
		}
	//var theform = obj.form;
	//alert(theform.name);
	var tabtonext = false;
	var i = getElementIndexSendToPhone(obj);
	//alert(i);
	var j=i+1;
	if (j >= allelements.length) { j=0; }
	if (i == -1) { return; }
	while (j != i) {
		if ((allelements[i].id!="phone_area_code") && (allelements[i].id!="phone_first_three"))
			return;
		if ((allelements[i].id =="phone_area_code")) {
			var len = allelements[i].value.length;
			//alert(len);
			if (len == 3) {
				tabtonext = true;
				//alert("entered");
			}
		}
		if ((allelements[i].id =="phone_first_three")) {
			var len = allelements[i].value.length;
			if (len == 3)
				tabtonext = true;
		}
		//alert(tabtonext);
		if ((allelements[j].type!="hidden") && 
		    (allelements[j].id != allelements[i].id) && 
			(!allelements[j].disabled) && tabtonext) {
			allelements[j].focus();
			break;
			}
		j++;
		if (j >= allelements.length) { j=0; }
		}
}

function getElementIndex(obj) {
	//var theform = obj.form;
	var allelements = $$('div#device input');
	for (var i=0; i<allelements.length; i++) {
		if (obj.id == allelements[i].id) {
			return i;
			}
		}
	return -1;
}

function getElementIndexSendToPhone(obj) {
	//var theform = obj.form;
	var allelements = $$('div#sendtoFriend input');
	for (var i=0; i<allelements.length; i++) {
		if (obj.id == allelements[i].id) {
			return i;
			}
		}
	return -1;
}




//*********************************/

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 createParams(Params) {
	var querystr = "?";
	for(i=0;i<Params["keys"].length;i++) {
		querystr += Params["keys"][i]+"="+encodeURIComponent(Params["values"][i])+"&"; //or encodeURI
	}
	return querystr;
}