Event.observe(window,"load", function()
{

    function getURLParam(strParamName){
      var strReturn = "";
      var strHref = window.location.href;
      if ( strHref.indexOf("?") > -1 ){
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
          if (
    aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
            var aParam = aQueryString[iParam].split("=");
            strReturn = aParam[1];
            break;
          }
        }
      }
      return unescape(strReturn);
    }

    seoPath=getURLParam('seoPath');
	currentDate = new Date();
    loadAds=0;
    new Ajax.Request("/view/proj2/ajax/getSeoHash.php?nonce=" + currentDate.getTime(),
   	{
   		method: 'get',
   		parameters: {seoPath:seoPath},
   		onSuccess: function(transport)
        {
            if (location.hash=="")
            {
                data = transport.responseText.evalJSON();
                location.hash=data.seoHash;
            }
            else
            {
                loadAds=1;
            }
   	    }
   	});

   
    

	listingType = "mostPopular";
	pagercount = 0;
	initialSearchText = "Type here or click on tags below";
	$('searchBox').value = initialSearchText;

	//Show things hidden on showAd page
	$('dcsContainer').show();
	$('adnavContainer').show();
	$('pageNoBox1').show();
	$('pageNoBox2').show();

	/*************************************
		>>>>>>>>>DEFAULTS START<<<<<<<<<<<
	*************************************/
	MSIE = "Microsoft Internet Explorer";
	var iFrameStartSrc = "/view/iFrame/IEdummy.php?";
	ieLoaded = true;
	selectParams = "";
	currentlyLoading = -1;

	//alphacode is 'A'
	alphaCode = 65;

	pageNumber = 1;
	adPageNumber = 1;

	pageCoefficient = 2; //Must be an integer - How much larger the cloud will get when 'more' is clicked
	adLimit = 20;

	//Set as a specific one for the rbi sites

	selectedFromHash = "";
	locationSelectedFromHash = "";
	searchFromHash = "";
	currentHash = "-1";

	cloudName = "listcloud";
	cloudSwitch = false;
	tags = new Array();
	locationTags = new Array();
	CloudTags = new Array();
	topPage = 1;
	topPageAd = 1;
	numberOfTags = 0;
	shownTags = 0;
	topAdNumber = 0;

	if(typeof(locationTitle) == "undefined")
	{
		var locationTitle = "<li class='labelTag'>Location:</li>";
	}

	if(typeof(tagTitle) == "undefined")
	{
		var tagTitle = "<li class='labelTag'>Tag:</li>";
	}



	/*************************************
		>>>>>>>>>DEFAULTS STOP<<<<<<<<<<<<<
		>>>>>>>>>FUNCTIONS START<<<<<<<<<<<
	*************************************/

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

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

	eraseCookie = function(name)
	{
		createCookie(name,"",-1);
	};

	getSearch = function()
	{
		searchVal = "";
		try{
		searchObj = $('searchBox').value.toQueryParams();
		for(searchEl in searchObj)
		{
			searchVal += searchEl;
		}
		}
		catch(err)
		{
			alert("error"+err);
		}
		return searchVal;
	};

	setSearch = function(newVal)
	{
		$('searchBox').value = newVal.unescapeHTML();
	};

	//Regenerates selected tag list based on new array.
	updateLocationSelectedTagsHTML = function()
	{
		firstTag = true;
		$("selectedlocationTags").update("\r");
		newSel = "";
		locationTags.each(function(tag)
		{
			if(firstTag)
			{
				$("selectedlocationTags").insert("\r\t\n"+ locationTitle +"\r\t\n");
				firstTag = false;
			}

			$("selectedlocationTags").insert("\r\t\n"+tag.locationSelectedHTML()+"\r\t\n");
			$("locationremoveSelectedTag" + tag.id).observe("click", function()
			{
				pageTracker._trackEvent("LocationTag", "Remove", $('locationTagActualTitle' + tag.id).innerHTML);
				locationTags = returnWithoutLocationTag(tag.id);
				updateLocationSelectedTagsHTML();
				resetPageNums();
				loadCloud(true, true, false);
			});
		});
	};

	//Regenerates selected tag list based on new array.
	updateSelectedTagsHTML = function()
	{
		firstTag = true;
		$("selectedTags").update("\r");
		newSel = "";
		tags.each(function(tag)
		{
			if(firstTag)
			{
				$("selectedTags").insert("\r\t\n"+ tagTitle +"\r\t\n");
				firstTag = false;
			}

			$("selectedTags").insert("\r\t\n"+tag.selectedHTML()+"\r\t\n");
			$("removeSelectedTag" + tag.id).observe("click", function()
			{
				pageTracker._trackEvent("Tag", "Remove", $('tagActualTitle' + tag.id).innerHTML);
				tags = returnWithoutTag(tag.id);
				updateSelectedTagsHTML();
				resetPageNums();
				loadCloud(true, true, false);
			});
		});
	};

	//Returns the array of objects without the objects that have the given id.
	returnWithoutLocationTag = function(oldTagId)
	{
		temporaryArr = new Array();
		locationTags.each(function(tagIt)
		{
			if(tagIt.id != oldTagId)
			{
				temporaryArr.push(tagIt);
			}
		});
		return temporaryArr;
	};

	//Returns the array of objects without the objects that have the given id.
	returnWithoutTag = function(oldTagId)
	{
		temporaryArr = new Array();
		tags.each(function(tagIt)
		{
			if(tagIt.id != oldTagId)
			{
				temporaryArr.push(tagIt);
			}
		});
		return temporaryArr;
	};


	setTabs = function(tabType)
	{
		if(listingType == "mostPopular")
		{
			$("tt").addClassName('ttselected');
			if ($("mainTab") !== null)
			{
				$("mainTab").addClassName('mselected');
			}

			if($("az").hasClassName('azselected'))
			{
				$("az").removeClassName('azselected');
			}
			if($("locTab").hasClassName('locselected'))
			{
				$("locTab").removeClassName('locselected');
			}
		}
		else if(listingType == "abc")
		{
			$("az").addClassName('azselected');
			if($("tt").hasClassName('ttselected'))
			{
				$("tt").removeClassName('ttselected');
			}
			if($("locTab").hasClassName('locselected'))
			{
				$("locTab").removeClassName('locselected');
			}
			if ($("mainTab") !== null)
			{
				if($("mainTab").hasClassName('mselected'))
				{
					$("mainTab").removeClassName('mselected');
				}
			}
		}
		else if(listingType == "location")
		{
			$("locTab").addClassName('locselected');
			if($("tt").hasClassName('ttselected'))
			{
				$("tt").removeClassName('ttselected');
			}
			if($("az").hasClassName('azselected'))
			{
				$("az").removeClassName('azselected');
			}
			if ($("mainTab") !== null)
			{
				if($("mainTab").hasClassName('mselected'))
				{
					$("mainTab").removeClassName('mselected');
				}
			}
		}
	};

	changeListingType = function(newType)
	{
		pageTracker._trackEvent("Cloud", "ChangeListingType", newType);

		oldType = listingType;
		listingType = newType;
		setTabs();
		resetPageNums();

		loadCloud(true, false, false);
	};

	changeAlphaCode = function(newCode)
	{
		pageTracker._trackEvent("Cloud", "RestrictByAlpha", newCode);
		alphaCode = newCode;
		resetPageNums();
		loadCloud(true, false, false);
	};

	changePageNo = function(newNo)
	{
		//alert("new" +newNo );
		pageNumber = newNo;
		loadCloud(true, false, false);
	};

	changeAdPageNo = function(newNo)
	{
		adPageNumber = newNo;
		loadCloud(false, true, false);
	};

	changeAdLimit = function(newLimit)
	{
		adLimit = newLimit;
		changeAdPageNo(1);
	};

	$('adQuantitySelect').observe("change", function()
	{
		pageTracker._trackEvent("AdvertListings", "ChangeQuantity", "", $('adQuantitySelect').options[$('adQuantitySelect').selectedIndex].value);
		changeAdLimit($('adQuantitySelect').options[$('adQuantitySelect').selectedIndex].value);
	});

	//To accurately sort tags
	sortTag = function (a,b)
	{
		return a.id - b.id;
	};

	generatePageSelector = function()
	{
		//alert("page"+pageNumber+"top"+topPage);
		//Previous page
		if(pageNumber > 1)
		{
			$('downPage').show();
		}
		else
		{
			$('downPage').hide();
		}

		//Current page
		if (numberOfTags == "1")
		{
			tagWord = "tag";
		}
		else
		{
			tagWord = "tags";
		}
		$('numberTags').update(shownTags + " of " + numberOfTags + " " + tagWord);

		//Next page
		if(pageNumber < topPage)
		{
			$('upPage').show();
		}
		else
		{
			$('upPage').hide();
		}
	};

	generateAdPageSelector = function()
	{
		//Previous page
		if(adPageNumber > 1)
		{
			$('downPageAd').show();
			$('downPageAdBottom').show();
		}
		else
		{
			$('downPageAd').hide();
			$('downPageAdBottom').hide();
		}
		//Current page
		$('numberOfAds').update(topAdNumber + " adverts");
		$('numberOfAdsBottom').update(topAdNumber + " adverts");

		//Next page
		if(adPageNumber < topPageAd)
		{
			$('upPageAd').show();
			$('upPageAdBottom').show();
		}
		else
		{
			$('upPageAd').hide();
			$('upPageAdBottom').hide();
		}
	};

	//Resets cloud and advert page numbering
	resetPageNums = function()
	{
		pageNumber = 1;
		adPageNumber = 1;
		generatePageSelector();
		generateAdPageSelector();
	};

	//Remove tooltip
	closeTooltip = function(identity)
	{
			createCookie(identity,"set", 1000);
			$(identity).hide();
	};

	//Hitting enter in searchbox
	$("searchBox").observe("keypress", function(event)
	{
		if (event.keyCode == Event.KEY_RETURN)
		{
			pageTracker._trackEvent("Cloud", "Search", getSearch());
			resetPageNums();
			loadCloud(true, true, false);
		}
	});

	$("searchBox").observe("focus", function(event)
	{
		if(getSearch() == initialSearchText)
		{
			setSearch("");
		}
	});

	dcsUpPage = function()
	{
		pageTracker._trackEvent("Cloud", "UpPage", "", parseInt(adPageNumber, 10) + 1);
		changePageNo(parseInt(pageNumber, 10) + 1);
	};

	dcsDownPage = function()
	{
		pageTracker._trackEvent("Cloud", "DownPage", "", parseInt(adPageNumber, 10) - 1);
		changePageNo(parseInt(pageNumber, 10) - 1);
	};

	$('downPageAd').observe("click", function()
	{
		pageTracker._trackEvent("AdvertListings", "DownPage", "", parseInt(adPageNumber, 10) - 1);
		changeAdPageNo(parseInt(adPageNumber, 10) - 1);
	});

	$('upPageAd').observe("click", function()
	{
		pageTracker._trackEvent("AdvertListings", "UpPage", "", parseInt(adPageNumber, 10) + 1);
		changeAdPageNo(parseInt(adPageNumber, 10) + 1);
	});

	$('downPageAdBottom').observe("click", function()
	{
		pageTracker._trackEvent("AdvertListings", "DownPage", "", parseInt(adPageNumber, 10) - 1);
		changeAdPageNo(parseInt(adPageNumber, 10) - 1);
	});

	$('upPageAdBottom').observe("click", function()
	{
		pageTracker._trackEvent("AdvertListings", "UpPage", "", parseInt(adPageNumber, 10) + 1);
		changeAdPageNo(parseInt(adPageNumber, 10) + 1);
	});

	loadCloud = function(newTags, newAds, keepHash)
	{
        if(newAds)
        {
    		$('seoMainText').hide();
        }
		selectParams = "selected=";
		tags.sort(sortTag).each(function(tag)
		{
			selectParams += tag.id + "|";
		});
		selectParams += "&location=";
		locationTags.sort(sortTag).each(function(tag)
		{
			selectParams += tag.id + "|";
		});
		selectParams += "&listingType=" + listingType;
		selectParams += "&alphaCode=" + alphaCode;
		if(getSearch() == initialSearchText)
		{
			searchOutput = "";
		}
		else
		{
			searchOutput = getSearch();
		}
		selectParams += "&searchText=" + searchOutput;
		selectParams += "&pageNo=" + pageNumber;
		selectParams += "&adPageNo=" + adPageNumber;
		selectParams += "&adLimit=" + adLimit;

		if(clientRestrict != null)
		{
			selectParams += "&clientRestriction=" + clientRestrict;
		}

		//Creates history event asap (i.e. not after everything has happened
		if(!keepHash)
		{
			pagercount++;
			if(MSIE == navigator.appName)
			{
				location.hash = selectParams;
				$("hiddeniFrameForIE").src = "/view/iFrame/IEdummy.php?" + selectParams + "&nonce=";
				ieLoaded = false;
			}
			else
			{
				//alert("newhashis\n" + selectParams);
				location.hash = selectParams;
			}

			//alert("iframehash\n"+ Element.extend(frames['hiddeniFrameForIEName'].document.getElementById('hashParagraph').innerHTML).unescapeHTML() + "\ncurrenthash\n" + currentHash +"\nurlhash\n" +location.hash);
			//document.title = "how"+pagercount;
		}
		currentlyLoading = -2;
		//stop checking for hash changes
		checkHash = false;

		if(newTags)
		{
			$("tagCloudLoading").show();
		}

		if(newAds)
		{
			$("advertLoading").show();
			$('adnav').update("");
		}

		if(listingType == "location")
		{
			$('pageNo').hide();
		}
		else
		{
			$('pageNo').show();
		}



		currentHash = "#" + selectParams;
		currentDate = new Date();

		//This is done at the last moment so it doesn't affect the hash url (and screw up forward/back)
		if(newTags)
		{
			selectParams += "&newTags=1";
		}
        if(newAds)
		{
			selectParams += "&newAds=1";
		}
        

		something = new Ajax.Request("/view/proj2/ajax/tagCloud.php?nonce=" + currentDate.getTime(),
		{
			method: 'get',
			parameters: selectParams,
			onSuccess: function(transport)
			{
				pageTracker._trackPageview("DCSAjaxCall"+selectParams);

					newContents = transport.responseText.evalJSON();

					if(newTags)
					{
						$("listcloud").update("\r");

						if(listingType == "abc")
						{
							alphaTop  = "<ul id='A-Zlistcloud' class='listcloud'>";
							for (i= 65; i<= 90; i++)
							{
								selected = "";
								if(i == alphaCode)
								{
									selected = " id='selected' ";
								}

								usefulAlphaLink = "unavailable";
								if(newContents.alphaCount.indexOf(String.fromCharCode(i).toLowerCase()) != -1)
								{
									usefulAlphaLink = "available";
								}

								alphaTop += "<li><a class='"+ usefulAlphaLink + "'" + selected +"href='javascript:changeAlphaCode(" + i + ")'>" +
								String.fromCharCode(i) + "</a></li>";
							}
							alphaTop += "</ul>";
							$("listcloud").insert(alphaTop);
						}

						noTags = true;
						CloudTags = new Array();

						newContents.cloud.each(function(tag)
						{
							noTags = false;
							tempTag = new Tag(tag.id, tag.title, tag.weight);
							CloudTags[tag.id] = tempTag;

							if(listingType == "location")
							{
								$(cloudName).insert(tempTag.locationCloudHTML());
								$("locationtag" + tag.id).observe('click', function()
								{
									pageTracker._trackEvent("LocationTag", "Add", $('locationTagActualCloudTitle' + tag.id).innerHTML);
									$("locationtag" + tag.id).remove();
									locationTags.push(CloudTags[tag.id]);
									updateLocationSelectedTagsHTML();
									resetPageNums();
									loadCloud(true, true, false);
								});
							}
							else
							{
								$(cloudName).insert(tempTag.cloudHTML());

								$("tag" + tag.id).observe('click', function()
								{
									pageTracker._trackEvent("Tag", "Add", $('tagActualCloudTitle' + tag.id).innerHTML);
									$("tag" + tag.id).remove();
									tags.push(CloudTags[tag.id]);
									updateSelectedTagsHTML();
									resetPageNums();
									loadCloud(true, true, false);
								});
							}
						});

						if(noTags)
						{
							$(cloudName).insert("<li>No more tags are available in that combination.<br /> Widen your search by removing one or more tags from your list above.</li>");
						}

						//Get cloud top page.

						shownTags = newContents.shownTags;
						topPage = newContents.maxPages;
						numberOfTags = newContents.numTags;
						generatePageSelector();
						$("tagCloudLoading").hide();
					}



					/****************END OF CLOUD
					START OF ADVERTS************/
					generateAdPageSelector();
					if(newAds)
					{
					    $('adnav').insert(newContents.adListing);

					    $("advertLoading").hide();
					}
					topAdNumber = newContents.numAdPages;
				    topPageAd = newContents.maxAdPages;
				    generateAdPageSelector();
				    
				if(!keepHash)
				{
					pagercount++;
					if(MSIE != navigator.appName)
					{
						//start checking for hash changes again
						checkHash = true;
					}

					//alert("iframehash\n"+ Element.extend(frames['hiddeniFrameForIEName'].document.getElementById('hashParagraph').innerHTML).unescapeHTML() + "\ncurrenthash\n" + currentHash +"\nurlhash\n" +location.hash);
					//document.title = "how"+pagercount;
				}

				shownToolTip = false;
				//Tags tab
				
				$$('.toolTipClass').each(function(el)
				{
					el.hide();
				});

				//Tag tab
				if(listingType == "mostPopular")
				{
					//No more tags
					if(noTags)
					{
						$("tooltipNoTags").hide();
						//The tooltip exists
						if($("tooltipNoTags") !== null)
						{
							//The cookie isn't set
							if(readCookie("tooltipNoTags") === null)
							{
								//No other tooltips are shown
								if(!shownToolTip)
								{
									shownToolTip = true;
									$("tooltipNoTags").show();
								}
							}
						}
					}
					//There are tags to choose
					else if(tags.size() == 0)
					{
						//The tooltip exists
						if($("tooltipTags") !== null)
						{
							//The cookie isn't set
							if(readCookie("tooltipTags") === null)
							{
								//No other tooltips are shown
								if(!shownToolTip)
								{
									shownToolTip = true;
									//Display it
									$("tooltipTags").show();
								}
							}
						}
					}
					else if(tags.size() == 1)
					{
						//The tooltip exists
						if($("tooltipTags1Chosen") !== null)
						{
							//The cookie isn't set
							if(readCookie("tooltipTags1Chosen") === null)
							{
								//No other tooltips are shown
								if(!shownToolTip)
								{
									shownToolTip = true;
									//Display it
									$("tooltipTags1Chosen").show();
								}
							}
						}
					}
				}
				else if(listingType == "location")
				{
					//There are some tags to choose
					if(!noTags)
					{
						//The tooltip exists
						if($("tooltipTagsLocation") !== null)
						{
							//The cookie isn't set
							if(readCookie("tooltipTagsLocation") === null)
							{
								//No other tooltips are shown
								if(!shownToolTip)
								{
									shownToolTip = true;
									//Display it
									$("tooltipTagsLocation").show();
								}
							}
						}
					}
				}
			}
		});
	};

	/*************************************
		>>>>>>>>>FUNCTIONS STOP<<<<<<<<<<<
		>>>>>>>>>CLASS START<<<<<<<<<<<<<<
	*************************************/
	Tag = function(id, title, weight)
	{
		this.title = title;
		this.id = id;
		this.weight = weight;

		this.cloudHTML = function()
		{
			return "\r\t\n<li id='tag"+ this.id +"'>\r\t\n<a id='tagActualCloudTitle"+ this.id +"' class='tag"+ this.weight + "'>"+ this.title +"</a>\r\t\n</li>\r\t\n";
		};
		this.selectedHTML = function()
		{
			anchorText = "";
			returnWithoutTag(this.id).each(function(tag)
			{
				anchorText += tag.id + "|";
			});
			return "\r\t\n<li class='selected'>\r\t\n<a class='filterDel' id='removeSelectedTag"+ this.id +"'>&nbsp;</a>\r\t\n<span id='tagActualTitle"+ this.id +"'>" + this.title +"</span>\r\t\n</li>";
		};

		this.locationCloudHTML = function()
		{
			return "\r\t\n<li id='locationtag"+ this.id +"'>\r\t\n<a id='locationTagActualCloudTitle"+ this.id +"' class='locationtag"+ this.weight + "'>"+ this.title +"</a>\r\t\n</li>\r\t\n";
		};
		this.locationSelectedHTML = function()
		{
			anchorText = "";
			returnWithoutLocationTag(this.id).each(function(tag)
			{
				anchorText += tag.id + "|";
			});
			return "\r\t\n<li class='selected'>\r\t\n<a class='filterDel' id='locationremoveSelectedTag"+ this.id +"'>&nbsp;</a>\r\t\n<span id='locationTagActualTitle"+ this.id +"'>" + this.title +"</span>\r\t\n</li>\r\t\n";
		};
	};


	$('goSearch').observe("click", function()
	{
		pageTracker._trackEvent("Cloud", "Search", getSearch());
		resetPageNums();
		loadCloud(true, true, false);
	});


	/*************************************
		>>>>>>>>>CLASS STOP<<<<<<<<<<<<<<
	*************************************/

	/*
		Go through the hash loading variables
		substring removes #
	*/
	loadFromHash = function(loadingHash)
	{
		currentlyLoading = loadingHash;
		loadingHash.substring(1).split("&").each(function(hashEl)
		{
			if(hashEl.startsWith("selected="))
			{
				selectedFromHash = hashEl;
			}
			else if(hashEl.startsWith("location="))
			{
				locationSelectedFromHash = hashEl;
			}
			else if(hashEl.startsWith("listingType="))
			{
				listingType = hashEl.split("=")[1];
			}
			else if(hashEl.startsWith("alphaCode="))
			{
				alphaCode = hashEl.split("=")[1];
			}
			else if(hashEl.startsWith("searchText="))
			{
				searchFromHash = hashEl;
			}
			else if(hashEl.startsWith("pageNo="))
			{
				pageNumber = hashEl.split("=")[1];
			}
			else if(hashEl.startsWith("adPageNo="))
			{
				adPageNumber = hashEl.split("=")[1];
			}
			else if(hashEl.startsWith("adLimit="))
			{
				adLimit = hashEl.split("=")[1];
				if(adLimit == 10)
				{
					$('adQuantitySelect').selectedIndex = 0;
				}
				else if(adLimit == 20)
				{
					$('adQuantitySelect').selectedIndex = 1;
				}
				else if(adLimit == 50)
				{
					$('adQuantitySelect').selectedIndex = 2;
				}
				else if(adLimit == 100)
				{
					$('adQuantitySelect').selectedIndex = 3;
				}
			}
			else if(hashEl.startsWith("clientRestriction="))
			{
				clientRestrict = hashEl.split("=")[1];
			}
		});

		something = new Ajax.Request("/view/proj2/ajax/loadHashTags.php?nonce=" + currentDate.getTime(),
		{
			method: 'get',
			parameters: selectedFromHash,
			onSuccess: function(transport)
			{
				tagsFromHash = transport.responseText.evalJSON();
				tags = new Array();
				tagsFromHash.tags.each(function(tag)
				{
					newTag = new Tag(tag.id, tag.title, "");
					tags.push(newTag);
				});
				updateSelectedTagsHTML();

				something = new Ajax.Request("/view/proj2/ajax/loadLocationHashTags.php?nonce=" + currentDate.getTime(),
				{
					method: 'get',
					parameters: locationSelectedFromHash,
					onSuccess: function(transport)
					{
						locationTags = new Array();
						tagsFromHash = transport.responseText.evalJSON();
							tagsFromHash.tags.each(function(tag)
							{
								newTag = new Tag(tag.id, tag.title, "");
								locationTags.push(newTag);
							});
						updateLocationSelectedTagsHTML();

						something = new Ajax.Request("/view/proj2/ajax/returnSearch.php?nonce=" + currentDate.getTime(),
						{
							method: 'get',
							parameters: searchFromHash,
							onSuccess: function(transport)
							{
								searchJSON = transport.responseText.evalJSON();
								if(searchJSON.searchText == "")
								{
									searchJSON.searchText = initialSearchText;
								}
								setSearch(searchJSON.searchText);
								setTabs();
                                if(loadAds)
                                {
    								loadCloud(true, true, false);                                    
                                }
                                else
                                {
    								loadCloud(true, false, false);                                    
                                    loadAds=1;
                                }
							}
						});
					}
				});
			}
		});
	};
	firstNavCheck = true;
	checkHash = true;

    function checkForUrlChanges()
	{
	try
	{


		if(ieLoaded === false)
		{
			if(currentHash == Element.extend(frames['hiddeniFrameForIEName'].document.getElementById('hashParagraph').innerHTML).unescapeHTML())
			{
				ieLoaded = true;
				checkHash= true;
			}
		}

		if(checkHash === true)
		{
			//Broken up for readability
			if(navigator.appName == MSIE)
			{
				//If coming from back from an ad view, an IM link, a ...
				if(firstNavCheck)
				{
					//alert("firstview");
					iFrameStore = location.hash;
					firstNavCheck = false;
				}
				else
				{
					iFrameStore = Element.extend(frames['hiddeniFrameForIEName'].document.getElementById('hashParagraph').innerHTML).unescapeHTML();
				}
				iFrameStore = decodeURI(iFrameStore);

				if(currentHash != iFrameStore && currentlyLoading != iFrameStore)
				{
					//alert("1" +currentHash + "\n2" + currentlyLoading  + "\n3" +iFrameStore);
					loadFromHash(iFrameStore);
				}
			}
			else
			{
				if (currentHash != location.hash && currentlyLoading != location.hash)
				{
					//alert("1" +currentHash + "\n2" + currentlyLoading  + "\n3" +location.hash);
					loadFromHash(location.hash);
				}
			}
		}
		//when the dcs is mid-load and the forward/back button is pressed
//		else
//		{
//			if(!firstNavCheck)
//			{
//				testParams = forTestParams;
//				//Broken up for readability
//
//				if(navigator.appName == MSIE)
//				{
//					iFrameStore = Element.extend(frames['hiddeniFrameForIEName'].document.getElementById('hashParagraph').innerHTML).unescapeHTML();
//					iFrameStore = decodeURI(iFrameStore);
//					if(testParams !== iFrameStore && currentlyLoading !== iFrameStore && ieLoaded === true)
//					{
//						loadFromHash(iFrameStore);
//					}
//
//				}
//				else
//				{
//					if (testParams != location.hash && currentlyLoading != location.hash)
//					{
//						loadFromHash(location.hash);
//					}
//				}
//			}
//		}
		firstNavCheck = false;
	}

	catch(err)
	{
		alert("erris"+err.message);
	}
	}
    window.setTimeout(checkForUrlChanges,1000)

    function startRegularChecks()
    {
        periodExecute = new PeriodicalExecuter(checkForUrlChanges, 0.1);
    }
    window.setTimeout(startRegularChecks,2000)


});
