Event.observe(window, 'load', page_loaded, false);

/********************************************************************************
Please note that page_loaded event is fired only once as the entire page does not
refresh at all in BoostCDP
*******************************************************************************/
function page_loaded(evt) {

		initialize();
		setHistory();
		if ($('keysearchfield')) {
			$('keysearchfield').focus();
		}
		
		//set omniture variables first time
		//s.pageName = "BoostLive";
		s.pageName = "RingTones & More";
		s.prop2 = s.pageName;
		s.prop21 = s.pageName;
		
		s.channel = "Shop";
		var s_code=s.t();
		if(s_code) document.write(s_code);
		Event.observe('buckets_containerI', 'click', set_omniture_variables_bucketI, false);
		Event.observe('buckets_containerII', 'click', set_omniture_variables_bucketII, false);

	//var winhref = window.location.href;
	//if (winhref.indexOf("jumpURL=Y") != -1 && winhref.indexOf("itemtype=app") != -1) {
	
		//alert("hello");
		//alert($('app1Btn').id);
		//transitI($('app1Btn').childNodes[0],'app');
		
		//var appobject = new ApplicationJump('app1Btn');
		//appobject.fx.bind(appobject);
	//}
  
  	//Event.observe('tabs', 'click', tab_clicked,false);
  
}

function clear_omniture_variables() {

	s.pageName = "";
	s.channel = "";
	s.prop21 = "";
	s.prop2 = "";
	s.products = "";
	s.events = "";
	s.eVar2 = "";
	s.eVar3 = "";
	s.eVar4 = "";
}

function set_omniture_variables_bucketI(evt) {

	clear_omniture_variables();
	//s.pageName = "BoostLive";
	var current_node = Event.element(evt);
	//alert('in set_omniture_variables_bucketI');
	var node_clicked = current_node.parentNode;
	if (node_clicked.id == 'rtBtn' || node_clicked.id == 'wpBtn' || node_clicked.id == 'gameBtn') {
		//var bucket_node = node_clicked.parentNode.parentNode;
		//var channel_name_variable = bucket_node.getAttribute("bucket_title");
		//s.pageName = node_clicked.getAttribute("title") + " & More";
		s.pageName = node_clicked.getAttribute("title") + " Category";
		//s.prop2 = s.pageName;
		s.prop2 = "Customize Your Phone";
		if (node_clicked.id == 'gameBtn')
			s.prop2 = "get entertainment";
		//s.prop21 = s.pageName;
		s.prop21 = s.pageName + "> What's Hot";
		//alert(channel_name_variable);
		s.channel = "Shop";
		var s_code=s.t();
		if(s_code) document.write(s_code);
		//void(s.t());
		//alert(channel_name_variable);
	}
	else { // for Applications
		var bucket_node = current_node.parentNode;
		//alert(bucket_node.id);
		var itemtype = bucket_node.getAttribute("itemtype");
		
		//alert(itemtype);
		if (itemtype == 'app') {
			var categorytext = bucket_node.getAttribute("cattext");
			//alert(categorytext);
			s.channel = "Shop";
			s.prop2 = "Add Applications";
			s.pageName = categorytext + " Category";
			s.prop21 = categorytext + " Category";
			var s_code=s.t();
			if(s_code) document.write(s_code);
		}
	}
	
	//alert(s.channel);
	//alert(s.prop2);
	//alert(s.pageName);
	//alert(s.prop21);
	
	Event.stop(evt);

}

function set_omniture_variables_bucketII(evt) {

	clear_omniture_variables();
	
	s.channel = "Shop";
	s.prop2 = "Customize Your Phone";
	var current_node = Event.element(evt);
	
	//var node_clicked = current_node.parentNode;
	var node_clicked = current_node;
	//alert(node_clicked.id);
	if ($(node_clicked.id) && node_clicked.id.indexOf("cat") != -1) {
		//if (node_clicked.id == 'rtBtn' || node_clicked.id == 'wpBtn' || node_clicked.id == 'gameBtn' || node_clicked.id.indexOf("app") != -1) {
		var bucket_node = node_clicked;
		//alert(bucket_node.id);
		var itemtype = bucket_node.getAttribute("itemtype");
		var categorytext = bucket_node.getAttribute("cattext");
		
		switch(itemtype) {
			case 'rt':
				s.pageName = "Ringtones Category";
				s.prop21 = "Ringtones Category > " + categorytext;
				break;
			case 'wp':
				s.pageName = "Wallpapers Category";
				s.prop21 = "Wallpapers Category > " + categorytext;
				break;
			case 'game':
				s.pageName = "Games Category";
				s.prop21 = "Games Category > " + categorytext;
				break;
			
		}
		
		var s_code=s.t();
		if(s_code) document.write(s_code);
		//void(s.t());
		//alert(channel_name_variable);
	}
	
	Event.stop(evt);

}

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

	Function called onComplete of ItemDetails

*************************************************************************/
function set_omniture_variables_itemdetails(itemId,itemDesc) {

	//Don't clear variables here
	
	s.prop21 = s.prop21 + itemDesc;
	//alert(itemDesc);
	s.products = s.products + itemId;
	s.events = "prodView";
	/*alert(s.prop21);
	alert(s.pageName);
	alert(s.channel);
	alert(s.prop2);
	alert(s.products);*/
	var s_code=s.t();
	if(s_code) document.write(s_code);
		

}

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

	Function called onComplete of SendtoPhone

*************************************************************************/
function set_omniture_variables_downloadconfirmation(ptn,error,itemtypename,itemid,itemprice) {

	//Don't clear variables here
	if ('Y' == error) {
	
		s.pageName = "Download Error:  Invalid PTN number";
		s.channel = "Shop";
		s.prop2 = "";
		s.prop21 = "Download Error: Invalid PTN Number > "+itemtypename;
		s.events = "";
		s.products = "";
		//s.events = "Purchase";
		//alert("Omniture variables : s.pageName="+s.pageName+" s.channel="+s.channel+" s.prop21="+s.prop21+" s.events="+s.events);
		var s_code=s.t();
		if(s_code) document.write(s_code);
	
	}
	else {
		s.pageName = "Download Confirmation";
		s.channel = "Shop";
		s.prop2 = "";
		s.events = "Purchase";
		//Products (single item)	s.products = ';[Download Product ID];[Download Units];[Download Price]'	 e,g s.products = ';ring0123;1;2.99'
		var itemid_suffix = "";
		if (itemtypename == 'RingTones')
			itemid_suffix = "ring";
		if (itemtypename == 'Wallpapers')
			itemid_suffix = "wall";
		if (itemtypename == 'Games')
			itemid_suffix = "games";
		if (itemtypename == 'Application')
			itemid_suffix = "app";
		s.products = itemid_suffix+itemid+";1;"+itemprice;
		//alert("Omniture variables : s.pageName="+s.pageName+" s.channel="+s.channel+" s.events="+s.events+" s.products="+s.products);
		var s_code=s.t();
		if(s_code) document.write(s_code);
	}
	
	//alert(s.prop21);
	//alert(s.pageName);
	//alert(s.channel);
	//alert(s.prop2);
	//alert(s.prop21);
	//alert(s.products);
	

}

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

	Function called for Search,Device Filtering and Artist Search
	evar2 for Phone model needs to be passed

*************************************************************************/
function set_omniture_variables_top(flag,eVarvalue,deviceName) {

	//Device - Downloads
	//s.eVar2 = [phone model ID]
	//s.eVar2 = i425
	//Search Term - Downloads
	//s.eVar3 = [search term, converted to lowercase]
	//s.eVar3 = the wire
	//Artist - Downloads
	//s.eVar4 = [artist dropdown list item]

	clear_omniture_variables();
	switch (flag) {
		case "2":
			s.eVar2 = eVarvalue; //here evarValue itself is the device name
			break;
		case "3": //for globalsearch
			s.eVar3 = eVarvalue.toLowerCase();
			s.eVar2 = deviceName;
			break;
		case "4":
			s.eVar4 = eVarvalue;
			s.eVar2 = deviceName;
			break;

	}
	
	//alert(s.eVar2);
	//alert(s.eVar3);
	//alert(s.eVar4);
	var s_code=s.t();
	if(s_code) document.write(s_code);
		

}

//since url on top does not change , make sure it does not happen twice
var firsttimejumptab = 'Y';
function jumpToAppTab() {

	var winhref = window.location.href;
	//alert(winhref);
	if (winhref.indexOf("jumpURL=Y") != -1 && winhref.indexOf("itemtype=app") != -1 && firsttimejumptab == 'Y') {
		firsttimejumptab = 'N';
		transitI($('app1Btn').childNodes[0],'app');
	}

}

//declaring the class
var ApplicationJump = Class.create();

//var appObj = {
ApplicationJump.prototype = {

	   initialize: function(objname) {
	   		alert(objname);
			this.appobject = $(objname);
			//assigning our method to the event
			
	   },
	   
	   fx: function() {     
	   		alert(this.appobject.id);
	   		//transitI($('app1Btn').childNodes[0],'app');
	   }
};



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;
}

/****************************************************************
Cookie Related Functions
*****************************************************************/

function createCookie(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=/";
}

/*function readCookie(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;
}*/

function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function deleteCookie(name, path)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            //((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
/***********************************************************
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);
}

/**********************
Validate Phone Number
******************************/ 

function CheckPhoneNumber(PhoneNo,TagStr)

{

	// get rid of non-numerics

	var checkOK = new String("0123456789");
	//var strNo = new String(PhoneNo);
	var strNo = PhoneNo;
	
	if (strNo == 'undefined' || strNo == null || strNo.length < 1) {
		alert("Phone Number cannot be blank");
		return false;
	}

	PhoneNo="";
	for ( i = 0; i < strNo.length; i++ )

	{
		ch = strNo.charAt(i);

		for (j = 0;  j < checkOK.length;  j++)

			if (ch == checkOK.charAt(j))

				break;

		if (j != checkOK.length)

		{
			PhoneNo=String(PhoneNo)+String(ch);
		}
	}

	// get rid of leading 1

	if ( ( PhoneNo.length == 11 ) && ( PhoneNo.charAt(0) == 1 ) )

	{

		PhoneNo = PhoneNo.substr(1,10);

	}



	if ( (PhoneNo.length != 0) && (PhoneNo.length < 10) )
	{
		alert("Please enter exactly 10 digits in \"" + TagStr + "\".");
		PhoneNo.focus();
		return false;
	}

	if (PhoneNo.length > 10)
	{
		alert("Please enter exactly 10 digits in \"" + TagStr + "\".");
		PhoneNo.focus();
		return false;
	}

	var checkStr = PhoneNo;
	var allValid = true;
	var decPoints = 0;
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
		break;
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
	}
	if (!allValid)
	{
		alert("Please enter only digits in \"" + TagStr + "\".");

		PhoneNo.focus();

		return false;

	}
	if ( checkStr.length == 10 )
	{
		if ( checkStr.charAt(0) < '2' )
		{
			alert("The first digit of the area code in \"" + TagStr + "\" cannot be a '1' or '0'");

			PhoneNo.focus();

			return false;

		}
		if ( checkStr.charAt(3) < '2' )
		{
			alert("The first digit of the prefix in \"" + TagStr + "\" cannot be a '1' or '0'");

			PhoneNo.focus();

			return false;

		}
		if ( checkStr.substring(0,3) == "900" )
		{
			alert("The area code in \"" + TagStr + "\" cannot be '900'");
			PhoneNo.focus();
			return false;
		}
	}
	
	//else {
		return true;
		//alert("OK");
	//}	
}


/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

// --------------------------------------------------------------------- 
// Called From 			:		All pages request ajax calls
//
// Language Used		:		Javascript
//
// Description	 		:		Get the innerHTML with reespect to an AJAX Call
//	
//
// Parameters Passed	:		url to call with parameters abd the div id of the innerHTML
// 
// Returns              :       
// 																	   
// Author				:		Jyoti					   
// --------------------------------------------------------------------- 


function ajaxpage(url, containerid,asynccall){
	
	//document.getElementById(containerid).innerHTML= "<img src='images/loading.gif'/>";
	//document.getElementById(containerid).innerHTML="<div class='load'><img src='images/loading.gif'/></div>";
	switch(containerid) {
	
		case "phone":
		case "selectArtistNameBox":
			document.getElementById(containerid).innerHTML="<div class='load'><img src='images/loading_bar.gif'/></div>";
			break;
		default:
			document.getElementById(containerid).innerHTML= "<div class='load'></div>";
			break;
	
	}
	
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
		page_request.onreadystatechange=function(){
			loadpage(page_request, containerid)
		}
	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
	if (asynccall == '1')
		page_request.open('GET', url+bustcacheparameter, true)
	else {
		//instead of using request.open("uri", "GET", true) you could use request.open("uri", "GET", false) to make it a synchronous call and have the scripting environment wait until the document is received
		page_request.open('GET', url+bustcacheparameter, false)
	}
	page_request.send(null)

	//if using post
	//page_request.open("POST",url+bustcacheparameter, true); 
	//page_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	//var str = "pet=dog&hobby=painting"; 
	//page_request.send(str);

}

function loadpage(page_request, containerid){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
	//alert(page_request.responseText);
	document.getElementById(containerid).innerHTML=page_request.responseText;
}


function loadobjs(){
	if (!document.getElementById)
	return
	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1){ //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
		else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
}

/*********************************************
  Getting values by looping through form
// --------------------------------------------------------------------- 
// Called From 			:		Not used currently kept as reference
//
// Language Used		:		Javascript
//
// Description	 		:		looping through form Values
//	
//
// Parameters Passed	:		
// 
// Returns              :       
// 																	   
// Author				:		Jyoti					   
// --------------------------------------------------------------------- */

function getFormValues(fobj){ 
	var str = ""; 
	for(var i = 0;i < fobj.elements.length;i++) { 
		switch(fobj.elements[i].type){ 
			case "text": 
			case "textarea": 
			case "password": 
				if (!fobj.elements[i].disabled) str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&"; 
				break; 
			case "hidden": 
				//hidden cannot be disabled 
				str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&"; 
				break; 
			case "checkbox": 
			case "radio": 
				if(fobj.elements[i].checked && !fobj.elements[i].disabled) str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].value) + "&"; 
				break; 
			case "select-one": 
				if (!fobj.elements[i].disabled) str += fobj.elements[i].name + "=" + encodeURIComponent(fobj.elements[i].options[fobj.elements[i].selectedIndex].value) + "&"; 
				break; 
			case "select-multiple": 
				if (!fobj.elements[i].disabled){ 
					for (var j = 0; j < fobj.elements[i].length; j++){ 
						var optElem = fobj.elements[i].options[j]; 
						if (optElem.selected == true){ 
							str += fobj.elements[i].name + "[]" + "=" + encodeURIComponent(optElem.value) + "&"; 
						} 
					} 
				} 
				break; 
		} 
	} 
	//Strip final &amp; 
	str = str.substr(0,(str.length - 1)); 
	return str; 
} 


/**
// --------------------------------------------------------------------- 
// Called From 			:		in All function creating query params for Ajax
//
// Language Used		:		Javascript
//
// Description	 		:		creating query params for Ajax
//	
//
// Parameters Passed	:		var Params = new Array("keys","values");		
		
		// Keys
		Params["keys"] = Array	("key1","key2"	);

		// Values
		Params["values"] = Array	(value1,value2);
		The encodeURI function will encode content as UTF-8 characters
	The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.
	http://xkr.us/articles/javascript/encode-compare/

// 
// Returns              :       The query parameters formed as name value pairs
// 																	   
// Author				:		Jyoti					   
// --------------------------------------------------------------------- 
** Declaration should be like this

**/

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;
}


// --------------------------------------------------------------------- 
// Called From 			:		contenttypes.jsp
//
// Language Used		:		Javascript
//
// Description	 		:		Filters Content Type By Phone
//	
//
// Parameters Passed	:		DeviceParams["keys"] = Array	("deviceid");
// 
// Returns              :       
// 																	   
// Author				:		Jyoti					   
// --------------------------------------------------------------------- 

function getContentTypeByDevice() {
	c = 0;
	var deviceid = $('txtdeviceid').value;
	
	if (isEmptyStr(deviceid))
		deviceid = 0;
	
	var DeviceParams = new Array("keys","values");		
	DeviceParams["keys"] = Array	("deviceid");
	DeviceParams["values"] = Array	(deviceid);
	//alert(deviceid);
	var url = "contenttypes.do"+createParams(DeviceParams);
	
	ajaxpage(url,'buckets_containerI','1');
	//ajaxLoader(url,'buckets_containerI');
}

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

	Fired after pressing enter for global search
***********************************************************************************/
function OnKeyPressOfGlobalSearch() {

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

 

				
//function bucketpaginate(formname,act,commandvalue,listtype,totalrows,offsetval) {
//source denotes the pagination is for categories,subcategories or artists in the bucket region
function bucketpaginate(contenttype,commandvalue,offsetval,totalrows,source) {

		

		var deviceid = $('txtdeviceid').value;
	
		if (isEmptyStr(deviceid))
			deviceid = 0;
			
		var sync_var_bucket_2 = 0;
		var sync_var_bucket_3 = 0;
			
		var bucket_2_url = '';
		if (contenttype == 'rt' || contenttype == 'music' ||contenttype == 'ct') {
		
			if (source == 'genre')
				bucket_2_url = $('txtbucketII_top_Url').value;
			else
				bucket_2_url =  $('txtbucketIIUrl').value;
		}
		else
			bucket_2_url = $('txtbucketIIUrl').value;
		//alert("URL Before:"+location_url);
		var bucket_2_query = fleegix.uri.getQuery(bucket_2_url);
		var bucket_2_url_base = fleegix.uri.getBase(bucket_2_url); //portion before the question mark
		bucket_2_query = fleegix.uri.setParam('pager.offset', offsetval, bucket_2_query);
		var bucket_2_urlandparams = bucket_2_url_base + "?" + bucket_2_query;
		
		var bucket_3_url = $('txtbucketIIIUrl').value;
		//alert("URL Before:"+location_url);
		var bucket_3_query = fleegix.uri.getQuery(bucket_3_url);
		var bucket_3_url_base = fleegix.uri.getBase(bucket_3_url); //portion before the question mark
		bucket_3_query = fleegix.uri.setParam('pager.offset', offsetval, bucket_3_query);
		var bucket_3_urlandparams = bucket_3_url_base + "?" + bucket_3_query;
		
		if (source == 'subgenre' && contenttype != 'rt' && contenttype != 'ct' && contenttype != 'music') {
			bucket_3_query = fleegix.uri.setParam('subgenrepaginate', 'Y', bucket_3_query);
		}
			
		
		//alert("bucket_2_urlandparams="+bucket_2_urlandparams);
		//alert("bucket_3_urlandparams="+bucket_3_urlandparams);
		
		var bucket_2_opt = {
					    // Use POST
					    method: 'post',asynchronous:true,
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: bucket_2_query, 
					    onCreate: function() {
					    	if (sync_var_bucket_2 == 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>';
				       			//$('buckets_containerII').innerHTML = "<div class='load'></div>";
				       			
				    	},
					     // Handle successful response
					    onSuccess: function(t) {
					    	sync_var_bucket_2 = 1;
					    	var resp = t.responseText; //getting the disbaled array from here
					        //alert(resp);
					        $('buckets_containerII').innerHTML = resp;
					        
					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
					    	if (contenttype == 'rt' || contenttype == 'music' || contenttype == 'ct')
					        	$('txtbucketII_top_Url').value = bucket_2_urlandparams;
					        $('txtbucketIIUrl').value = bucket_2_urlandparams;
							//setHistory();
					    }
					}
					
		
		 var bucket_3_opt = {
					    // Use POST
					    method: 'post',asynchronous:true,
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: bucket_3_query, 
					    onCreate: function() {
					    	if (sync_var_bucket_3 == 0)
					    		$('buckets_containerIII').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>';
				       			//$('buckets_containerIII').innerHTML = "<div class='load'></div>";
				       			
				       		
				    	},
					     // Handle successful response
					    onSuccess: function(t) {
					    	sync_var_bucket_3 = 1;
					    	var resp = t.responseText; //getting the disbaled array from here
					        //alert(resp);
					        $('buckets_containerIII').innerHTML = resp;
					        
					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
					        $('txtbucketIIIUrl').value = bucket_3_urlandparams;
							//setHistory();
					    }
					}

		var parentcategoryvalue = $('txtcategoryid').value;
		//alert($('txtcategoryid').value);
		switch(contenttype) {
			  case 'rt':
			  		switch(source) {
			  			case 'genre':
					  		//var urlandparams = "ringtones.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
							//ajaxLoader(urlandparams,'buckets_containerII');
							new Ajax.Request('ringtones.do', bucket_2_opt);
							break;
						case 'subgenre':
							//alert('in subgenre of bucketpaginate');
							//var parentcategorytext = $('subgenre_listing').getAttribute("parentcategorytext");
							//var urlandparams = "ringtones.do?subgenrepaginate=Y&categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&parentcategorytext="+parentcategorytext+"&deviceid="+deviceid;
							//ajaxLoader(urlandparams,'buckets_containerII');
							bucket_2_query = fleegix.uri.setParam('subgenrepaginate', 'Y', bucket_2_query);
							//alert('rt subcategory bucket_2_query='+bucket_2_query);
							ajaxpage('ringtones.do?'+bucket_2_query,'buckets_containerII','1');
							//new Ajax.Request('ringtones.do', bucket_2_opt);
							break;
						case 'artist':
							//var categoryforartist = $('artist_listing').getAttribute("selectedcategory");
							//var Params = new Array("keys","values");		
							//Params["keys"] = Array	("deviceid","command","categorysearchvalue","pager.offset");
					  		//Params["values"] = Array	(deviceid,"rtartistbycat",categoryforartist,offsetval);
					  		//var url_1 = "ringtones.do"+createParams(Params);
					  		//alert(url_1);
					  		new Ajax.Request('ringtones.do', bucket_3_opt);
					  		//ajaxpage(url_1,'buckets_containerIII','1');
							
							break;
					}
					break;
					
			 case 'wp':
			 case 'game':
			 case 'app':
			  		switch(source) {
			  			case 'genre':
					  		//var urlandparams = "wallpapers.do?categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&deviceid="+deviceid;
							//ajaxLoader(urlandparams,'buckets_containerII');
							new Ajax.Request(bucket_2_url_base, bucket_2_opt);
							break;
						case 'subgenre':
							//alert('in subgenre of bucketpaginate');
							//var parentcategorytext = $('subgenre_listing').getAttribute("parentcategorytext");
							//var urlandparams = "wallpapers.do?subgenrepaginate=Y&categorysearchvalue="+parentcategoryvalue+"&command="+commandvalue+"&pager.offset="+offsetval+"&parentcategorytext="+parentcategorytext+"&deviceid="+deviceid;
							//ajaxLoader(urlandparams,'buckets_containerIII');
							
							//alert('Other than rt subcategory bucket_3_query='+bucket_3_query);
							new Ajax.Request(bucket_3_url_base, bucket_3_opt);
							break;
						
					}
					break;
		}
		
		
}

function contentpaginate(command,offsetval,totalrows,itemtype) {

		var global_search_itemtype = "";	
		var sync_var_content = 0;
		//For Global Search for first time when the first tab gets selected
		if ($('ul_keyword_search'))
			global_search_itemtype = $('ul_keyword_search').getAttribute("itemtype");
			
		
		var location_url = $('txtContentUrl').value;
		//alert("URL Before:"+location_url);
		
		//For promotions , get the itemtype from the parameter
		if (location_url.indexOf("promotions.do") != -1) {
			global_search_itemtype = itemtype;
		}
		var query = fleegix.uri.getQuery(location_url);
		var url_base = fleegix.uri.getBase(location_url); //portion before the question mark
		query = fleegix.uri.setParam('pager.offset', offsetval, query);
		if (!isEmptyStr(global_search_itemtype))
				query = fleegix.uri.setParam('itemtype', global_search_itemtype, query);
		
		var urlandparams = url_base + "?" + query;
		//alert("Final URL:"+urlandparams);
		$('txtContentUrl').value = urlandparams;
		
	  	//alert(params);
  		var opt = {
		    // Use POST
		    method: 'post',asynchronous:true,
		    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
		    postBody: query, //to get rid of ?
		    onCreate: function(t) {
		    	//alert('loading');
		    	if (sync_var_content == 0)
		       		$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
		    },
		     // Handle successful response
		    onSuccess: function(t) {
		    	sync_var_content = 1;
		    	var resp = t.responseText; //getting the disbaled array from here
		        //alert(resp);
		        $('content').innerHTML = resp;
		        
		    },
		   
		     // On Complete acts as a postfunction
		    onComplete: function(t) {	
	
				//Keep the omniture variables same as before and resend them
				//alert(s.channel);
				//alert(s.prop2);
				//alert(s.pageName);
				//alert(s.prop21);
				var s_code=s.t();
				if(s_code) document.write(s_code);
		    
				setHistory();
		    }
		}
		
		new Ajax.Request(url_base, opt);

}

/*** Fired when the tab for contentytypes like RT,WP is changed in global artist search***/
function OnChangeOfTabforArtistSearch(itemtype) {
			
		var sync_var_content = 0;
		var location_url = $('txtContentUrl').value;
		//alert("URL Before:"+location_url);
		var query = fleegix.uri.getQuery(location_url);
		var url_base = fleegix.uri.getBase(location_url); //portion before the question mark
		query = fleegix.uri.setParam('itemtype', itemtype, query);
		
		var urlandparams = url_base + "?" + query;
		//alert("Final URL:"+urlandparams);
		$('txtContentUrl').value = urlandparams;
		
	  	//alert(params);
  		var opt = {
		    // Use POST
		    method: 'post',asynchronous:true,
		    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
		    postBody: query,
		    onCreate: function(t) {
		    	//alert('loading');
		    	if (sync_var_content == 0)
		       		$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
		    },
		     // Handle successful response
		    onSuccess: function(t) {
		    	sync_var_content = 1;
		    	var resp = t.responseText; //getting the disbaled array from here
		        //alert(resp);
		        $('content').innerHTML = resp;
		        
		    },
		   
		     // On Complete acts as a postfunction
		    onComplete: function(t) {
				setHistory();
		    }
		}
		
		new Ajax.Request(url_base, opt);

}

/*** Fired when the sorting tab the data on the Content portion is clicked like Title,Artist,Newest***/
function SortDataBy(sortby) {

		var location_url = $('txtContentUrl').value;
		//alert("URL Before:"+location_url);
		var query = fleegix.uri.getQuery(location_url);
		var url_base = fleegix.uri.getBase(location_url); //portion before the question mark
		query = fleegix.uri.setParam('pager.offset', '0', query);
		//var urlandparams = url_base + "?" + query;
		//alert("Final URL:"+urlandparams);
	
	var itemtype = "";	
	if ($('ul_keyword_search'))
		itemtype = $('ul_keyword_search').getAttribute("itemtype");
		
		
	var urlandparams = '';
	switch(sortby) {
	
		case 'newest':
			//alert($('txtsortByNewest').value);
			query = fleegix.uri.setParam('sortby', $('txtsortByNewest').value, query);
			if (!isEmptyStr(itemtype))
				query = fleegix.uri.setParam('itemtype', itemtype, query);
			urlandparams = url_base + "?" + query;
			break;
			
		case 'title':
			query = fleegix.uri.setParam('sortby', $('txtsortByTitle').value, query);
			if (!isEmptyStr(itemtype))
				query = fleegix.uri.setParam('itemtype', itemtype, query);
			urlandparams = url_base + "?" + query;
			break;
			
		case 'rank':
			query = fleegix.uri.setParam('sortby', $('txtsortByRanking').value, query);
			if (isEmptyStr(itemtype) == false)
				query = fleegix.uri.setParam('itemtype', itemtype, query);
			urlandparams = url_base + "?" + query;
			break;
			
		case 'artist':
			query = fleegix.uri.setParam('sortby', $('txtsortByArtist').value, query);
			if (!isEmptyStr(itemtype))
				query = fleegix.uri.setParam('itemtype', itemtype, query);
			urlandparams = url_base + "?" + query;
			break;
	
	
	}
	var sync_var_content = 0;
	$('txtContentUrl').value = urlandparams;
	//alert("Final URL:"+urlandparams);
	var opt = {
	    // Use POST
	    method: 'post',asynchronous:true,
	    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
	    postBody: query, //to get rid of ?
	    onCreate: function(t) {
	    	//alert('loading');
	    	if (sync_var_content == 0)
	       		$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
	    },
	     // Handle successful response
	    onSuccess: function(t) {
	    	sync_var_content = 1;
	    	var resp = t.responseText; //getting the disbaled array from here
	        //alert(resp);
	        $('content').innerHTML = resp;
	        
	    },
	   
	     // On Complete acts as a postfunction
	    onComplete: function(t) {
	    
	    	//Keep the omniture variables same as before and resend them
			//alert(s.channel);
			//alert(s.prop2);
			//alert(s.pageName);
			//alert(s.prop21);
			var s_code=s.t();
			if(s_code) document.write(s_code);
			
			setHistory();
	    }
	}

	if (!isEmptyStr(urlandparams))
		new Ajax.Request(url_base, opt);
		//ajaxpage(urlandparams,'content','1');

 }

/*** Fired when the listings dropdown is changed in content portion ***/
function OnChangeOfSelectList(el,listvalue,itemtype,command) {

	for( var i = 0; el.parentNode.childNodes[i]; i++ ){
		el.parentNode.childNodes[i].className = '';
	}
	el.className = 'selected';
	
	var header = el.parentNode.parentNode.id+'Head';
	
	document.getElementById(header).innerHTML = el.innerHTML;
	

	el.parentNode.parentNode.className = "hide";
	
	var global_search_itemtype = "";	
	if ($('ul_keyword_search'))
		global_search_itemtype = $('ul_keyword_search').getAttribute("itemtype");

	var location_url = $('txtContentUrl').value;
	//alert("URL Before:"+location_url);
	var query = fleegix.uri.getQuery(location_url);
	var url_base = fleegix.uri.getBase(location_url); //portion before the question mark
	var query = fleegix.uri.setParam('rowspercolumn', listvalue, query);
	if (!isEmptyStr(global_search_itemtype))
		query = fleegix.uri.setParam('itemtype', global_search_itemtype, query);
	query = fleegix.uri.setParam('pager.offset', '0', query);
	var urlandparams = url_base + "?" + query;
	//alert("Final URL:"+urlandparams);
	$('txtContentUrl').value = urlandparams;
	
	//So that its set for everything else from now on
	$('txtlistNumValue').value = listvalue;
	
	ajaxpage(urlandparams,'content','1');
	
	

}


		//function OnChangeOfAlpha(val,indexval) {
		/****
		
		This function is used in two modes .. artistname is never passed so in most of the cases it is called
		as OnChangeOfAlpha(val) ; but only when you come from jumpURL for search by artist , the function is called 
		as OnChangeOfAlpha(val,artistname) , so that artist name becomes selected . It is called in such a mode
		from boostdefault.jsp where jump urls are handled.
	
		**************************************************************************************************/
		function OnChangeOfAlpha(val,artistname) {
			//alert('selectAlpha');
			var alphaselector = document.getElementById("artist_alpha");
			//var lis = obj.parentNode.getElementsByTagName('li');
			var lis = alphaselector.getElementsByTagName('li');
			//alert(alphaselector.id);
			if (alphaselector) {
				//alert(val);
				var displayvalue = '';
				for (var i=0; i<lis.length; i++) {
					//if (i == (indexval -1)) {
					if (lis[i].getAttribute("livalue") == val) {
						lis[i].className = 'selected';
						displayvalue = lis[i].innerHTML; //for A-B , display value is A , but val parameter comes as A-B
					}
					else
						lis[i].className = '';
				}
				//alert(alphaselector.parentNode.parentNode.id);
				toggle_element(alphaselector.parentNode.id);
				//var artistalphaVal = document.getElementById("selectedArtistalphaVal");
				//artistalphaVal.innerHTML = val;
				$('selectArtistAlphaHead').innerHTML = displayvalue;
				
				//Check if any devices are selected
				var deviceid = $('txtdeviceid').value;
				
				if (isWhitespace(deviceid))
					deviceid = 0;
				
				var AlphaParams = new Array("keys","values");		
				AlphaParams["keys"] = Array	("command","alphavalue","deviceid");
				AlphaParams["values"] = Array	("artistbyalpha",val,deviceid);
				
				//$('command').value = "alphaforartist";
				$('txtAlphaValue').value = val;
				//$('txtAlphaIndex').value = indexval;
				
				var params = createParams(AlphaParams);
				
				//var url = "artists.do"+createParams(AlphaParams);
				
				//alert(url);
				//ajaxpage(url,'selectArtistNameBox','1');
				
				$('selectArtistNameBox').innerHTML="<div class='load'><img src='images/loading_bar.gif'/></div>";
				
				var opt = {
				    // Use GET
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params.substr(1), //to get rid of ?
				    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
				        //alert(resp);
				        $('selectArtistNameBox').innerHTML = resp;
				        
				    },
				   
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    	 if (!isEmptyStr(artistname))
				        	$('selectArtistNameHead').innerHTML = artistname;
				    }
				}
			
				new Ajax.Request('artists.do', opt);
				
				/*var opt = {
				    // Use POST
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params.substr(1), //to get rid of ?
				   
				    // Handle Loading
				    onLoading: function() {
				    	 //alert('Loading Artists');
				    	//$('selectArtistNameBox').innerHTML="<div class='load'><img src='images/loading_bar.gif'/></div>";
				       
				    },
				     // Handle successful response
				    onSuccess: function(t) {
				    	var resp = t.responseText; //getting the disbaled array from here
				        //alert(resp);
				        $('selectArtistNameBox').innerHTML = resp;
				        
				    },
				    // Handle 404
				    on404: function(t) {
				        alert('Error 404: location "' + t.statusText + '" was not found.');
				    },
				    // Handle other errors
				    onFailure: function(t) {
				        alert('Error ' + t.status + ' -- ' + t.statusText);
				    },
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				        //alert('On Complete ' + t.status + ' -- ' + t.statusText);
				        if (!isEmptyStr(artistname))
				        	$('selectArtistNameHead').innerHTML = artistname;
 
				    }
				}
			
				new Ajax.Request('artists.do', opt);*/
			
				
				
			}
			
		}
		
		/**** To Get Results for Search By Artists in content ****/
		
		//function OnChangeOfArtist(val,indexval,rowspercol,offsetvalue) {
		function OnChangeOfArtist(val,rowspercol,offsetvalue) {
			
			//alert('OnChangeOfArtist'+val);
				
			var page_offset = offsetvalue;
			if (isEmptyStr(page_offset))
				page_offset = '';
				
			try {
				var artistselector = document.getElementById("artists");
				var lis = artistselector.getElementsByTagName('li');
				if (artistselector) {
					//alert(val);
					var selectedtext = '';
					//for (var i=0; i<lis.length; i++) { 
					for (var i=1; i<=lis.length; i++) { //because of Select Artist in the dropdown
						//lisHTMl is in plain format which no encoding like 4Ever (feat. Calapeso)
						var lisHTML = lis[i-1].innerHTML;
						var artistvalue_attribute = lis[i-1].getAttribute("artistvalue");
						var parameter_value = '';
						//var decodedval = URLDecode(val);
						if (lisHTML.indexOf('&amp;') != -1) {
							lisHTML=lisHTML.replace("&amp;","&");
							//lisHTML = URLEncode(lisHTML);
							parameter_value = URLDecode(val);
						}
						else {
							parameter_value = URLDecode(val); //because value is encoded by str:encode which is actually Java URLEncoder
						}
						//if (lisHTML == decodedval) {
						//if (lisHTML == parameter_value) {
						if (artistvalue_attribute == URLDecode(val)) {
							lis[i-1].className = 'selected';
							selectedtext = lis[i-1].innerHTML;
							break;
						}
						else
							//lis[i].className = '';
							lis[i-1].className = '';
					}
					
					//alert(alphaselector.parentNode.parentNode.id);
					toggle_element(artistselector.parentNode.id);
					//var artistalphaVal = document.getElementById("selectedArtistalphaVal");
					//artistalphaVal.innerHTML = val;
					$('selectArtistNameHead').innerHTML = selectedtext;
					
					
					//Becuase Select Artist has  a value of '' , so do not do the remaining if artist valeu is empty
					if (isEmptyStr(val)) {
						$('selectArtistNameHead').innerHTML = "Select Artist ..";
						return;
					}
					
					//Check if any devices are selected
					var deviceid = $('txtdeviceid').value;
									
					if (isEmptyStr(deviceid))
						deviceid = 0;
						
					var rows_per_col = rowspercol;
					if (isEmptyStr(rows_per_col))
						rows_per_col = $('txtlistNumValue').value;
					
					
					var ArtistParams = new Array("keys","values");		
					ArtistParams["keys"] = Array	("command","artistvalue","deviceid","rowspercolumn","pager.offset");
					ArtistParams["values"] = Array	("globalsearchbyartists",val,deviceid,rows_per_col,page_offset);
					
					//document.getElementById("txtselectedArtistalphaVal").value=val;
					var params = createParams(ArtistParams);
					var url = "artists.do"+createParams(ArtistParams);
					$('txtContentUrl').value = url;
					$('command').value = "globalsearchbyartists";
					$('txtArtistValue').value = val;
					//$('txtArtistIndex').value = indexval;
					
					//Collapse the 3 buckets on top
					document.getElementById('buckets').className = 'buckets_home_short search';
	
					for( var i = 0; document.getElementById('bucketI_Type').childNodes[i]; i++ ){
						document.getElementById('bucketI_Type').childNodes[i].className = '';
					}
				
					for( var i = 0; document.getElementById('bucketII_Type').childNodes[i]; i++ ){
						document.getElementById('bucketII_Type').childNodes[i].className = '';
					}
				
					for( var i = 0; document.getElementById('bucketIII_Type').childNodes[i]; i++ ){
						document.getElementById('bucketIII_Type').childNodes[i].className = '';
					}
				
					document.getElementById('buckets_containerI_value').innerHTML = '';
					
					//alert(url);
					
			  		var sync_var_content = 0;
			  		var opt = {
					    // Use POST
					    method: 'post',asynchronous:true,
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: params.substr(1), //to get rid of ?
					    onCreate: function(t) {
					    	if (sync_var_content == 0)
				       			$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
				    	},
					     // Handle successful response
					    onLoading: function(t) {
					    	//alert('loading');
				    	},
					    onSuccess: function(t) {
					    	sync_var_content = 1;
					    	var resp = t.responseText; //getting the disbaled array from here
					        //alert(resp);
					        //if (resp.indexOf("is not supported for this device") == -1)
					        	$('content').innerHTML = resp;

					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
							setHistory();
							
							set_omniture_variables_top("4",val,$('txtselected_device_name').value);
					    }
					}
			
					new Ajax.Request('artists.do', opt);
					
					//ajaxpage(url,'content','1');
				}
			}
			catch(Exception) {
				alert("In Exception");
			}
		}
		
		/**** getting the Alpha Values from backend to display in the drodown **/
		
		function getAlphaValues() {
		
				var deviceid = $('txtdeviceid').value;
								
				if (isWhitespace(deviceid))
					deviceid = 0;
					
				var Params = new Array("keys","values");		
				Params["keys"] = Array	("command","deviceid");
				Params["values"] = Array	("alphaforartist",deviceid);
				var params = createParams(Params);
				//alert(params);
				
				var opt = {
				    // Use POST
				    method: 'post',asynchronous:true,
				    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
				    postBody: params.substr(1), //to get rid of ?
				   
				    // Handle Loading
				    //onLoading: function() {
				       // alert('Loading');
				    //},
				     // Handle successful response
				    onSuccess: function(t) {
				    	var resp = t.responseText; //getting the disbaled array from here
				        //alert(resp);
				        $('selectArtistAlphaBox').innerHTML = resp;
				        
				    },
				    // Handle 404
				    on404: function(t) {
				        alert('Error 404: location "' + t.statusText + '" was not found.');
				    },
				    // Handle other errors
				    onFailure: function(t) {
				        alert('Error ' + t.status + ' -- ' + t.statusText);
				    },
				     // On Complete acts as a postfunction
				    onComplete: function(t) {
				    	var firstval = $('artistalphaVal1').getAttribute('livalue');
				    	//OnChangeOfAlpha(firstval,'1');
				    	OnChangeOfAlpha(firstval);
				    	toggle_element('selectArtistAlpha');
				    }
				}
			
				new Ajax.Request('artists.do', opt);
					
		}
		
/******* get Lists for the default page *************/	
function getListItems(listid,container,commandvalue) {
	
	var deviceid = $('txtdeviceid').value;
					
	if (isWhitespace(deviceid))
		deviceid = 0;
		
	var Params = new Array("keys","values");		
	Params["keys"] = Array	("command","deviceid","listid");
	Params["values"] = Array	(commandvalue,deviceid,listid);
	var params = createParams(Params);
	//alert(params);
	
	var opt = {
	    // Use POST
	    method: 'post',
	    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
	    postBody: params.substr(1), //to get rid of ?
	   
	    // Handle Loading
	    onCreate : function() {
		    $(container).innerHTML = '<div style="text-align:center !important; width:200px; height:100px; 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);
	        $(container).innerHTML = resp;
	        
	    },
	    // Handle 404
	    on404: function(t) {
	        alert('Error 404: location "' + t.statusText + '" was not found.');
	    },
	    // Handle other errors
	    onFailure: function(t) {
	        alert('Error ' + t.status + ' -- ' + t.statusText);
	    },
	     // On Complete acts as a postfunction
	    onComplete: function(t) {
	    }
	}

	new Ajax.Request('lists.do', opt);		
}

/*********************************************************************************************
		This function is fired when external lists are involved with banners

***************************************************************************************************/
function handleExternalLists(externalURL) {

		//var externalURL = 'boostdefault.do?jumpURL=Y&command=itemdetails&itemtype=bundle&itemId=110769';
		//alert(externalURL);
		var query = fleegix.uri.getQuery(externalURL);
		var url_base = fleegix.uri.getBase(externalURL); //portion before the question mark
		
		if (url_base.indexOf("boostdefault.do") == -1) {
		
			if(!isEmptyStr(query))
				url_base = url_base + "?" + query;
			window.location.href = url_base;
			return;
		}

		var itemtype = fleegix.uri.getParam('itemtype',query);
		var command = fleegix.uri.getParam('command',query);
		var deviceid = $('txtdeviceid').value;
		if (isEmptyStr(deviceid))
			deviceid = '0';
		
		var rowspercolumn = $('txtlistNumValue').value;
		if (isEmptyStr(rowspercolumn))
			setListNum(); //to set the rows per column
		
		switch(command) {
			case 'globalsearchbykeyword':
			
				//boostdefault.do?jumpURL=Y&command=globalsearchbykeyword&itemtype=<contenttype>&dlSearchField=<serach value or title of the item>
				
				var keyserachfield = fleegix.uri.getParam('dlSearchField',query);
				/*if (isEmptyStr(itemtype)) {
					alert('ItemType cannot be null or empty');
					return;
				}*/
				$('keysearchfield').value = keyserachfield;
				//alert($('keysearchfield').value);
				
				
				//alert("rowspercolumn:"+rowspercolumn);
				transitSearch(rowspercolumn,itemtype,'0');
				break;
				
			case 'globalsearchbyartists':
			
				//boostdefault.do?jumpURL=Y&command=globalsearchbyartists&artistvalue=ABBA
				var artistvalue = fleegix.uri.getParam('artistvalue',query);
				if (isEmptyStr(artistvalue)) {
					alert("ArtistValue cannot be empty");
					return;
				}

					//Formulate the alpha value from the first character
					if (!isEmptyStr(artistvalue)) {
						var alphavalue = artistvalue.substr(0,1).toUpperCase();
						//alert(alphavalue);
						if (!isLetter(alphavalue))
							alphavalue = 'MISC';
						else {
							if (alphavalue.indexOf("Z")  == -1) {
								//var asci_alpha = ascii_value(alphavalue);
								var str = new String(alphavalue);
								var asci_alpha = str.charCodeAt(0);
								var nextalpha = asci_alpha + 1;
								//alphavalue = alphavalue + '-' + asciitoChar(nextalpha);
								alphavalue = alphavalue + '-' + String.fromCharCode(nextalpha);
								
							}
							else
								alphavalue = alphavalue + '-';
						}
							
					}
					//alert(alphavalue);
					var ArtistParams = new Array("keys","values");		
					ArtistParams["keys"] = Array	("command","artistvalue","deviceid","rowspercolumn","pager.offset");
					ArtistParams["values"] = Array	("globalsearchbyartists",artistvalue,'0',rowspercolumn,'0');
					
					//document.getElementById("txtselectedArtistalphaVal").value=val;
					var params = createParams(ArtistParams);
					var url = "artists.do"+createParams(ArtistParams);
					$('txtContentUrl').value = url;
					$('command').value = "globalsearchbyartists";
					$('txtArtistValue').value = artistvalue;
					
					var sync_var_content = 0;
					var opt = {
					    // Use POST
					    method: 'post',
					    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
					    postBody: params.substr(1), //to get rid of ?
					     // Handle successful response
					    onCreate: function(t) {
					    	//alert('loading');
					    	if (sync_var_content == 0)
				       			$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
				    	},
					    onSuccess: function(t) {
					    	sync_var_content = 1;
					    	var resp = t.responseText; //getting the disbaled array from here
					        //alert(resp);
					        //if (resp.indexOf("is not supported for this device") == -1)
					        	$('content').innerHTML = resp;

					    },
					   
					     // On Complete acts as a postfunction
					    onComplete: function(t) {
					    
			    			OnChangeOfAlpha(alphavalue,artistvalue);
			    			toggle_element('selectArtistAlpha');
			    			
			    			//Collapse the 3 buckets on top
							document.getElementById('buckets').className = 'buckets_home_short search';
			
							for( var i = 0; document.getElementById('bucketI_Type').childNodes[i]; i++ ){
								document.getElementById('bucketI_Type').childNodes[i].className = '';
							}
						
							for( var i = 0; document.getElementById('bucketII_Type').childNodes[i]; i++ ){
								document.getElementById('bucketII_Type').childNodes[i].className = '';
							}
						
							for( var i = 0; document.getElementById('bucketIII_Type').childNodes[i]; i++ ){
								document.getElementById('bucketIII_Type').childNodes[i].className = '';
							}
						
							document.getElementById('buckets_containerI_value').innerHTML = '';

					    }
					}
			
					new Ajax.Request('artists.do', opt);
			break;
			
			case 'itemdetails':
			
				//boostdefault.do?jumpURL=Y&command=itemdetails&itemtype=rt&itemId=7894
				//or for bundle boostdefault.do?jumpURL=Y&command=itemdetails&itemtype=bundle&itemId=7894
				var itemtype = fleegix.uri.getParam('itemtype',query);
				if (isEmptyStr(itemtype)) {
					alert('Item Type is not specified in Jump URL properly.. Please specify itemtype parameter');
				}
				var itemId = fleegix.uri.getParam('itemId',query);
				if (isEmptyStr(itemId)) {
					alert('Item ID is not specified .. Please specify itemId parameter');
				}
				
				if (itemtype == 'bundle') {
				
						var ContentParams = new Array("keys","values");		
						ContentParams["keys"] = Array	("deviceid","command","itemId");
						ContentParams["values"] = Array	(deviceid,"bundleinlistdetails",itemId);
				  		url_content = "lists.do"+createParams(ContentParams);
				  		url_base = "lists.do";
				  		url_params = createParams(ContentParams);
				  		
				  		//alert(url_params);
				  		
					  	//ajaxpage('ringtones.do?command=rtdetails&itemId='+itemId,'content','1');				  	
					
						//Command value is always what action is performed on the results page i,e content div tag
						$('command').value = "bundleinlistdetails"; 
						var sync_var_content = 0;
							var opt = {
							    // Use POST
							    method: 'post',asynchronous:true,
							    //postBody: 'thisvar=true&thatvar=Howdy&theothervar=2112',
							    postBody: url_params.substr(1), //to get rid of ?
							     // Handle successful response
							    onCreate: function(t) {
							    	//alert('loading');
							    	if (sync_var_content == 0)
					       				$('content').innerHTML = '<div style="vertical-align:middle; text-align:center; background: url(images/loading.gif) center center no-repeat; padding:150px 0;"></div>';
					      			},
							    onSuccess: function(t) {
							    	sync_var_content = 1;
							    	var resp = t.responseText; //getting the disbaled array from here
							        $('content').innerHTML = resp;
					
							    },
							   
							     // On Complete acts as a postfunction
							    onComplete: function(t) {
							    	if ($('detail_phone_number')) {
							    		$('txtDetailsItemDesc').value = $('detail_phone_number').getAttribute("itemdesc");
							    		
							    	}
							    	$('txtContentUrl').value = url_content;
									setHistory();
							    }
							}
					
							new Ajax.Request(url_base, opt);
				
				}
				else {
					getItemDetails(itemtype,itemId,'');
				}
				document.getElementById('buckets').className = 'buckets_home_short search';
			break;
			
			case "searchbycategory":
				var categoryid = fleegix.uri.getParam('categoryid',query);
				jumpToCategorySearch(categoryid,itemtype);
				break;
				
			case "searchpromotions":
				var promoId = fleegix.uri.getParam('promotionid',query);
				transitPromo(promoId,'');
				
				break;
		}

}
		

/**For the implementation of the back button  in Ajax **/
        
      /** RSH must be initialized after the
    page is finished loading. */
//window.onload = initialize;
var historycounter = 0;
var bucket_I_hm;
var bucket_II_hm;
var bucket_III_hm;
var content_hm;
var top_hm; //to store the contents of the top menu like devices,globalsearch , artist

function initialize() {
  // initialize RSH
  dhtmlHistory.initialize();
 
  
  // add ourselves as a listener for history
  // change events
  dhtmlHistory.addListener(handleHistoryChange);
  
  // determine our current location so we can
  // initialize ourselves at startup
  var initialLocation = dhtmlHistory.getCurrentLocation();
  //alert("initialLocation:"+ initialLocation);
  
  // if no location specified, use the default
  if (initialLocation == null)
    initialLocation = "1";
  
  // now initialize our starting UI
  //updateUI(initialLocation, null);
  //counter++;
  //dhtmlHistory.add(""+counter+"", {message: document.getElementById("container").innerHTML});
  
  //Create three hashmaps for each bucket
  bucket_I_hm = new HashMap();
  bucket_II_hm = new HashMap();
  bucket_III_hm = new HashMap();
  content_hm = new HashMap();
  top_hm = new HashMap();
  
}

/** A function that is called whenever the user
    presses the back or forward buttons. This
    function will be passed the newLocation,
    as well as any history data we associated
    with the location. */
function handleHistoryChange(newLocation,
                             historyData) {
  // use the history data to update our UI
  updateUI(newLocation, historyData);                           
}

/** A simple method that updates our user
    interface using the new location. */
function updateUI(newLocation,historyData) {
                  
  var output = document.getElementById("container");
  
  // simply display the location and the
  // data
  //var historyMessage;
  //if (historyData != null)
    //historyMessage = historyData.message;
   
  //var message = "New location: "
                //+ newLocation 
                //+ ", history data="
                //+ historyMessage;
  
             
  //if (historyMessage != null) {
  	//var message = document.getElementById("container").innerHTML;
  	//message = "Location 1";
  	//alert(message);           
  	//output.innerHTML = historyMessage;
  //}
  
  	//alert("in Update UI");
  	var keycounter;
  	if (historyData != null)
    	keycounter = historyData.countervalue;
    //alert("keycounter"+keycounter);
    var hashkey = "messagekey"+keycounter;
    //alert(hashkey);
  	var savedObject = historyStorage.get(hashkey);
  	//alert(savedObject.message);
  	if (savedObject != null && savedObject.history_array != null) {
	  	var arr = savedObject.history_array;
	  	
	  	//For Home page with lists , refresh the page as
	  	//application call ia asnychronous and does not fetch data
	  	//so loading bar gets cached in history
	  	if (arr[0] == 'buckets_home') {
	  		window.location.href = 'boostdefault.do';
	  		return;
	  	}
	  	
		$('cm_nav').innerHTML = top_hm.get(hashkey);
		$('buckets_containerI').innerHTML = bucket_I_hm.get(hashkey);
		$('buckets_containerII').innerHTML = bucket_II_hm.get(hashkey);
		$('buckets_containerIII').innerHTML = bucket_III_hm.get(hashkey);
		$('content').innerHTML = content_hm.get(hashkey);
		
	  	
	  	$('buckets').className = arr[0];
	
	  	
	  	if ($('keysearchfield')) {
	  		  var keyvalue = arr[1];
	  		  if (keyvalue == 'undefined') keyvalue = '';
			  $('keysearchfield').value = keyvalue; 
		}
	}
  	
}

function setHistory() {
		//alert('here');
		//return;
		historycounter++;
		if (historycounter > 7) {
			historycounter = 1;
			/*for(j = 1;j <=7;j++) {
				var hashkey = "messagekey"+j;
				//if (historyStorage.hasKey(hashkey))
					//historyStorage.remove(hashkey);
					
				//bucket_I_hm.clear();
				//bucket_II_hm.clear();
				//bucket_III_hm.clear();
				//content_hm.clear();
				//top_hm.clear();
				if( bucket_I_hm.containsKey(hashkey))
					bucket_I_hm.remove(hashkey);
				if( bucket_II_hm.containsKey(hashkey))
					bucket_II_hm.remove(hashkey);
				if( bucket_III_hm.containsKey(hashkey))
					bucket_III_hm.remove(hashkey);
				if( content_hm.containsKey(hashkey))
					content_hm.remove(hashkey);
				
			}*/
		}
		var keycounter = ""+historycounter+"";
		//var msg = document.getElementById("container").innerHTML;
		//alert(msg);
		dhtmlHistory.add(""+historycounter+"", {countervalue: keycounter});
		
		var savedObject;
		
		//if (historyStorage.hasKey("message"))
    		//savedObject = historyStorage.get("message");
  		//else {
		    savedObject = new Object();
		    savedObject.id = keycounter;
		    savedObject.message = "";
		    savedObject.history_array = new Array();
		    /*savedObject.history_array[0] = $('buckets_containerI').innerHTML;
		    //savedObject.history_array[1] = $('buckets_containerII').innerHTML;
		    savedObject.history_array[1] = $('txtbucketIIUrl').value;
		    //savedObject.history_array[2] = $('buckets_containerIII').innerHTML;
		    savedObject.history_array[2] = $('txtbucketIIIUrl').value;
		    //savedObject.history_array[3] = $('content').innerHTML;
		    savedObject.history_array[3] = $('txtContentUrl').value;
		    savedObject.history_array[4] = $('buckets').className;
		    //savedObject.history_array[5] = $('content').innerHTML;
		    if ($('keysearchfield') && !isEmptyStr($('keysearchfield').value)) {
		    	savedObject.history_array[5] = $('keysearchfield').value;
		    }
		    else
		    	savedObject.history_array[5] = '';*/
		  
		    //savedObject.nestedObject = {someProp: "bye"};
		    //alert(savedObject.message);
		    
		    savedObject.history_array[0] = $('buckets').className;
		    if ($('keysearchfield') && !isEmptyStr($('keysearchfield').value)) {
		    	savedObject.history_array[1] = $('keysearchfield').value;
		    }
		    else
		    	savedObject.history_array[1] = '';
		    	
		    var allhashmapkey = "messagekey"+historycounter;
		     
		    if (historyStorage.hasKey(allhashmapkey))
				historyStorage.remove(allhashmapkey);
		    historyStorage.put(allhashmapkey, savedObject);
		    
		   
		    if( bucket_I_hm.containsKey(allhashmapkey))
		    	bucket_I_hm.remove(allhashmapkey);
		    if( bucket_II_hm.containsKey(allhashmapkey))
		    	bucket_II_hm.remove(allhashmapkey);
		    if( bucket_III_hm.containsKey(allhashmapkey))
		    	bucket_III_hm.remove(allhashmapkey);
		    if( content_hm.containsKey(allhashmapkey))
		    	content_hm.remove(allhashmapkey);
		    if( top_hm.containsKey(allhashmapkey))
		    	top_hm.remove(allhashmapkey);
		    	
		    bucket_I_hm.put(allhashmapkey,new String($('buckets_containerI').innerHTML));
			bucket_II_hm.put(allhashmapkey,new String($('buckets_containerII').innerHTML));
			bucket_III_hm.put(allhashmapkey,new String($('buckets_containerIII').innerHTML));
			//content_hm.put("messagekey"+historycounter,new String($('txtContentUrl').value));
			content_hm.put(allhashmapkey,new String($('content').innerHTML));
			top_hm.put(allhashmapkey,new String($('cm_nav').innerHTML));
			if ($('flash_nav'))
		    	$('flash_nav').className='';
		    setPos = setTimeout("clearFlashNavPosition()",500);
	   //}
		
}

function clearFlashNavPosition(){
	//alert($('flash_nav').className);
	if ($('flash_nav'))
		$('flash_nav').className='clear';
	//alert($('flash_nav').className);
}


/***********************************************************
	For implementation of Auto Complete TextBoxes for GlobalSearch
***************************************************************/

var isOpera = navigator.userAgent.indexOf('Opera') > -1; 
var isIE = navigator.userAgent.indexOf('MSIE') > 1 && !isOpera; 
var isMoz = navigator.userAgent.indexOf('Mozilla/5.') == 0 && !isOpera; 

var globalsearchedValuesArr = new Array();
//var globalsearchedValuesArr = ["red", "orange", "yellow", "green", "blue", "indigo", "violet", "brown"]; 

function textboxSelect (oTextbox, iStart, iEnd) { 

   switch(arguments.length) { 
       case 1: 
           oTextbox.select(); 
           break; 

       case 2: 
           iEnd = oTextbox.value.length; 
           /* falls through */ 
            
       case 3:          
           if (isIE) { 
               var oRange = oTextbox.createTextRange(); 
               oRange.moveStart("character", iStart); 
               oRange.moveEnd("character", -oTextbox.value.length + iEnd);      
               oRange.select();                                              
           } else if (isMoz){ 
               oTextbox.setSelectionRange(iStart, iEnd); 
           }                     
   } 

   oTextbox.focus(); 
} 

function textboxReplaceSelect (oTextbox, sText) { 

   if (isIE) { 
       var oRange = document.selection.createRange(); 
       oRange.text = sText; 
       oRange.collapse(true); 
       oRange.select();                                 
   } else if (isMoz) { 
       var iStart = oTextbox.selectionStart; 
       oTextbox.value = oTextbox.value.substring(0, iStart) + sText + oTextbox.value.substring(oTextbox.selectionEnd, oTextbox.value.length); 
       oTextbox.setSelectionRange(iStart + sText.length, iStart + sText.length); 
   } 

   oTextbox.focus(); 
} 

function autocompleteMatch (sText, arrValues) { 

   for (var i=0; i < arrValues.length; i++) { 
       if (arrValues[i].indexOf(sText) == 0) { 
           return arrValues[i]; 
       } 
   } 

   return null; 

} 

function autocomplete(oTextbox, oEvent, arrValues) { 

   switch (oEvent.keyCode) { 
       case 38: //up arrow  
       case 40: //down arrow 
       case 37: //left arrow 
       case 39: //right arrow 
       case 33: //page up  
       case 34: //page down  
       case 36: //home  
       case 35: //end                  
       case 13: //enter  
       case 9: //tab  
       case 27: //esc  
       case 16: //shift  
       case 17: //ctrl  
       case 18: //alt  
       case 20: //caps lock 
       case 8: //backspace  
       case 46: //delete 
           return true; 
           break; 

       default: 
           textboxReplaceSelect(oTextbox, String.fromCharCode(isIE ? oEvent.keyCode : oEvent.charCode)); 
           var iLen = oTextbox.value.length; 

           var sMatch = autocompleteMatch(oTextbox.value, globalsearchedValuesArr); 

           if (sMatch != null) { 
               oTextbox.value = sMatch; 
               textboxSelect(oTextbox, iLen, oTextbox.value.length); 
           }  
           
           return false; 
   } 
} 

// -------------------------------------------------------------------
// 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#detail_phone_number 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!="ptn1") && (allelements[i].id!="ptn2"))
			return;
		if ((allelements[i].id =="ptn1")) {
			var len = allelements[i].value.length;
			//alert(len);
			if (len == 3) {
				tabtonext = true;
				//alert("entered");
			}
		}
		if ((allelements[i].id =="ptn2")) {
			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; }
		}
}

//-------------------------------------------------------------------
// getElementIndex(input_object)
//   Pass an input object, returns index in form.elements[] for the object
//   Returns -1 if error
//-------------------------------------------------------------------
/*function getElementIndex(obj) {
	var theform = obj.form;
	for (var i=0; i<theform.elements.length; i++) {
		if (obj.name == theform.elements[i].name) {
			return i;
			}
		}
	return -1;
	}
	*/
function getElementIndex(obj) {
	//var theform = obj.form;
	var allelements = $$('div#detail_phone_number input');
	for (var i=0; i<allelements.length; i++) {
		if (obj.id == allelements[i].id) {
			return i;
			}
		}
	return -1;
}









