addLoadListener(setPageLinking);
addLoadListener(setSearchBox);
addLoadListener(onloadFilter);

function onloadFilter()
{
	if (location.hash) {
		ajaxInitiate(location.hash.replace("#filter/",""));
	}
}

function setSearchBox()
{
	if(!document.getElementById("innerSearchBoxForm"))
		{return false;}
	
	if(location.hash)
	{
		var params = location.hash.replace("#filter/","");
		params = params.split("&");
		for(i=0; i<params.length; i++)
		{
			if( params[i].indexOf("keywords") !=-1 )
			{
				var tmp = params[i].split("=");
				var filteredKeywords = tmp[1];
				document.getElementById("keywords").value = filteredKeywords;
			}
		}
	}
	
	var innerSearchBoxForm = document.getElementById("innerSearchBoxForm");

	innerSearchBoxForm.onsubmit = function() {
				if( document.getElementById("keywords").value=="" || document.getElementById("keywords").value == "Search for magazine")
				{
					document.getElementById("keywords").value="";
					document.getElementById("keywords").focus();
					return false;
				}
				var keywords = php_urlencode(document.getElementById("keywords").value);
				requestParam = "keywords="+keywords;
				if( document.getElementById(view_DIV)==null )
				{
					location = "http://www.joomag.com/en/magazines"+"?keywords="+keywords;
					return false;
				}
				location.hash = "filter/"+"keywords="+keywords;
				ajaxInitiate(requestParam);				
				return false;
		}
	document.getElementById("keywords").onfocus = function() {
						if( document.getElementById("keywords").value == "Search for magazine" )
						{
							document.getElementById("keywords").value = "";
						}
					}
	document.getElementById("keywords").onblur = function() {
						if( document.getElementById("keywords").value == "" )
						{
							document.getElementById("keywords").value = "Search for magazine";
						}
					}
}

function setPageLinking() {
	var paginatorLength = null;

	var upperLinks = document.getElementById("upperPaginator");
	if( upperLinks )
	{
		upperLinksCollection = upperLinks.getElementsByTagName("a");
		paginatorLength = upperLinksCollection.length
	}
	var lowerLinks = document.getElementById("lowerPaginator");
	if( lowerLinks )
	{
		lowerLinksCollection = lowerLinks.getElementsByTagName("a");
		paginatorLength = lowerLinksCollection.length
	}
	
	if( !lowerLinks && !upperLinks )
	{
		return false;
	}
	
	for (i=0;i<paginatorLength;i++) {
		if( upperLinks )
		{
			upperLinksCollection[i].onclick = function() {
					var clickedHREF = this.href.split("?");
					requestParam = clickedHREF[1];
					location.hash = "filter/"+clickedHREF[1];
					ajaxInitiate(requestParam);				
					return false;
			}
		}
		
		if( lowerLinks )
		{
			lowerLinksCollection[i].onclick = function() {
					var clickedHREF = this.href.split("?");
					requestParam = clickedHREF[1];
					location.hash = "filter/"+clickedHREF[1];
					ajaxInitiate(requestParam);				
					return false;
			}
		}
	}
}

function ajaxInitiate(requestParamStr) {
	if( requestParamStr!="" )
		requestParamStr += "&sbox="+searchIsON+"&mp="+mpIsON+"&cols="+mp_COLS+"&rows="+mp_ROWS;
	
	var ajaxCapable = getXhrObject();
	if (ajaxCapable)
	{
		AddClassName(document.getElementById(view_DIV), "process");
		ajaxCapable.onreadystatechange = function() {
											serverResponse(ajaxCapable);
										};
		ajaxCapable.open("POST", "http://www.joomag.com/getmagsresult.php", true);
		ajaxCapable.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajaxCapable.setRequestHeader("Content-length", requestParamStr.length);
		ajaxCapable.setRequestHeader("Connection", "close");

		ajaxCapable.send(requestParamStr);
	}
	else 
	{
		// document.getElementById("employee-info").innerHTML += "Your Browser Does not Support Ajax. To view this page, please disable JavaScript.";
	}
}

function serverResponse(ajaxCapable) {
	if (ajaxCapable.readyState == 4) {
		if (ajaxCapable.status == 200 || ajaxCapable.status == 304) {
			document.getElementById(view_DIV).innerHTML = ajaxCapable.responseText;
			RemoveClassName(document.getElementById(view_DIV), "process");
			setPageLinking();
			setSearchBox();
		}
	}
}

function getXhrObject() {  
	var xhrObject = false;
	// Most browsers (including IE7-IE8) use the 3 lines below
	if (window.XMLHttpRequest) {
		xhrObject = new XMLHttpRequest();
	}
	// Internet Explorer 5/6 will use one of the following
	else if (window.ActiveXObject) {
		try {   
		xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(err) {
				try {
				xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(err) {
				xhrObject = false;
				}
		}
	}
	return xhrObject;
}

// The code below is the load listener that helps run multiple events on the same page. All JS libraries have this built in.
function addLoadListener(fn)
{
	if (typeof window.addEventListener != 'undefined')
	{
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != 'undefined')
	{
		document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		var oldfn = window.onload;
		if (typeof window.onload != 'function')
		{
			window.onload = fn;
		}
		else
		{
			window.onload = function() {
										oldfn();
										fn();
									};
		}
	}
}

////////////
function AddClassName(objElement, strClass, blnMayAlreadyExist)
{
	// if there is a class
	if ( objElement.className )
	{
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// if the new class name may already exist in list
		if ( blnMayAlreadyExist )
		{
			// get uppercase class for comparison purposes
			var strClassUpper = strClass.toUpperCase();

			// find all instances and remove them
			for ( var i = 0; i < arrList.length; i++ )
			{
				// if class found
				if ( arrList[i].toUpperCase() == strClassUpper )
				{
					// remove array item
					arrList.splice(i, 1);
					// decrement loop counter as we have adjusted the array's contents
					i--;
				}
			}
		}

		// add the new class to end of list
		arrList[arrList.length] = strClass;

		// add the new class to beginning of list
		//arrList.splice(0, 0, strClass);

		// assign modified class name attribute
		objElement.className = arrList.join(' ');
	}
	// if there was no class
	else
	{
		// assign modified class name attribute      
		objElement.className = strClass;
	}
}

function RemoveClassName(objElement, strClass)
{
	// if there is a class
	if ( objElement.className )
	{
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// get uppercase class for comparison purposes
		var strClassUpper = strClass.toUpperCase();

		// find all instances and remove them
		for ( var i = 0; i < arrList.length; i++ )
		{
			// if class found
			if ( arrList[i].toUpperCase() == strClassUpper )
			{
				// remove array item
				arrList.splice(i, 1);
				// decrement loop counter as we have adjusted the array's contents
				i--;
			}
		}

		// assign modified class name attribute
		objElement.className = arrList.join(' ');
	}
}

function php_urlencode( s )
{
  return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}
   
function php_urldecode( s )
{
  return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
}