var srchArray = null;

function GetSearchAsArray() 
{
    if ( srchArray != null )
        return;
        
	srchArray = new Array();
	var input = location.search.substr(1);
	if (input) 
	{
		var arr = input.split("&");
        //alert(srchArray);
		var tempArray = new Array();
		for (var i = 0; i < arr.length; i++) 
		{
			tempArray = arr[i].split("=");
			srchArray[tempArray[0]] = tempArray[1];
        	//alert(tempArray[0]+","+tempArray[1]);
		}
	}
}

function insertInto( el, ins ) 
{ 
    if ( el.setSelectionRange )
    { 
        el.value = el.value.substring(0,el.selectionStart) + ins + el.value.substring(el.selectionStart,el.selectionEnd) + el.value.substring(el.selectionEnd,el.value.length); 
    } 
    else if (document.selection && document.selection.createRange) 
    { 
        el.focus(); 
        var range = document.selection.createRange(); 
        range.text = ins + range.text; 
    } 
}

function insertText( text )
{
    insertInto( document.getElementById( messageId ), text );
	return false;
}

function insertCode( start, end )
{
    insertInto( document.getElementById( messageId ), start + end );
	return false;
}

function PickAvatar( dir )
{
	if ( dir == 1 )
	{
		index++;
		if ( index == avatars.length )
			index = 0;
	}
	else
	{
		if ( index == 0 )
			index = avatars.length - 1;
		else
			index--;
	}
	
	document.getElementById( "avatar" ).value = avatars[index];
	document.getElementById( "avatarImage" ).src = "../Avatars/" + avatars[index];
}

function InitAvatar()
{
	document.getElementById( "avatarImage" ).src = "../Avatars/" + document.getElementById( "avatar" ).value;
}
		
function ShowObject( obj, show )
{
    obj = document.getElementById( obj );
    if ( obj != null )
    {
	    if ( show )
		    obj.style.display = "block";	
	    else
		    obj.style.display = "none";	
    }
}

function Reload( key, value )
{
    var params = "";
	var input = unescape(location.search.substr(1))
	var found = false;
	if (input) 
	{
		var srchArray = input.split("&")
		var tempArray = new Array()
		for (var i = 0; i < srchArray.length; i++) 
		{
			tempArray = srchArray[i].split("=")
			if ( tempArray[0] != key || value != null )
			{
			    if ( tempArray[0] == key )
			    {
			        found = true;
			        tempArray[1] = value;
			    }
			    else if ( tempArray[0] == "start" )
			        tempArray[1] = 0;

                if ( params.length == 0 )
	                params += "?" + tempArray[0] + "=" + escape( tempArray[1] );
    	        else
	                params += "&" + tempArray[0] + "=" + escape( tempArray[1] );
	        }
		}
	}
	
	if ( !found && value != null )
	{
        if ( params.length == 0 )
            params += "?" + key + "=" + escape( value );
	    else
            params += "&" + key + "=" + escape( value );
	}

    var path = location.pathname + params;	
    //alert( path );
    location.href = path;
    return false;
}

var sortColumn = "oa";
var sortOrder = "desc";

function UpdateFilter( home )
{
	GetSearchAsArray();
	
	if ( srchArray[ "in" ] != "forums" ) 
	{
	    var filter = "all";
	    if ( srchArray[ "ft" ] ) 
		    filter = srchArray[ "ft" ];
		var filterLink = document.getElementById( 'filter_' + filter);
		if ( filterLink != null )
		{
            document.getElementById( 'filter_' + filter).className = "sel";
            document.getElementById( 'searchFilter' ).value = filter;
        }
    }
        
    if ( !home )
    {
	    if ( srchArray[ "st" ] ) 
		    sortColumn = srchArray[ "st" ];
	    if ( srchArray[ "order" ] ) 
		    sortOrder = srchArray[ "order" ];
    		
	    if ( srchArray[ "search" ] )
	    {
	        //alert(srchArray[ "search" ]);
            document.getElementById( 'searchFor' ).value = decodeURIComponent( srchArray[ "search" ] );
        }
            
        document.onmouseup = OnMouseUp;
    }
}


var jddOther = null;
var jddCurrent = null;

function OnMouseUp(e)
{
    /*if (e == null) 
        e = window.event; 
    
    var target = e.target != null ? e.target : e.srcElement;*/
    
    if ( jddCurrent != null )
    {
        jddCurrent.style.display = "none";
        jddCurrent = null;
    }
    if ( jddOther )
    {
        jddOther.style.display = "block";
        jddOther = null;
    }
}

function JDDSelect( select, parent, value, auto )
{
    if ( auto )
        Reload( 'ft', value );
    else
    {
        document.getElementById( parent ).innerHTML = select.innerHTML;
        document.getElementById( parent + "Popup" ).style.display = "none";
        document.getElementById( parent + "Value" ).value = value;
        jddCurrent = null;
        if ( jddOther )
        {
            jddOther.style.display = "block";
            jddOther = null;
        }
    }
}

function JDDPopup( sub, other )
{
    if ( jddCurrent != null )
        jddCurrent.style.display = "none";
    
    var popup = document.getElementById( sub + "Popup" );
    if ( jddCurrent != null && popup.id == jddCurrent.id )
    {
        jddCurrent = null;
        return;
    }
    
    jddCurrent = popup;
    jddCurrent.style.display = "block";
    if ( other )
    {
        jddOther = document.getElementById( other + "Folder" );
        jddOther.style.display = "none";
    }
    else
        jddOther = null;
}

function JDDBuild( name, other, param, auto, labels, values )
{
	GetSearchAsArray();
	var current = srchArray[ param ];
	
	index = 0;
    var parent = document.getElementById( name + "Folder" );
    //var old = parent.innerHTML;
    //parent.innerHTML = "";
    for ( var i = 0; i < labels.length; i++ )
    {
        parent.innerHTML += "<div onclick=\"JDDSelect(this,'" + name + "','" + values[ i ]+ "'," + auto + ")\">" + labels[ i ] + "</div>";
        if ( current == values[ i ] )
            index = i;
    }

    if ( other != null )
        other = "'" + other + "'";
                    
    parent.innerHTML = "<div class='menuItem' onclick=\"JDDPopup('" + name + "'," + other + ")\"><div id='" + name + "'>" + labels[ index ] + "</div></div>"
        + "<div class='subMenu' id='" + name + "Popup'>"
        + parent.innerHTML + "</div>"
        + "<input type='hidden' id='" + name + "Value' value='" + values[ index ] + "' />";
        
    //alert(old+"\n\n"+parent.innerHTML);
}

function DoRecentSearch()
{

    var path = "../Home/Search.aspx?recent=1";
	if ( srchArray[ "ft" ] ) 
	    path += "&ft=" + srchArray[ "ft" ];
    //alert( path );
    location.href = path;
    return false;
}

function DoBasicSearch()
{
    var searchFor = document.getElementById( "searchString").value;
    var params = "../Home/Search.aspx?search=" + encodeURIComponent( searchFor );	
    var path = params;	
    //alert( path );
    location.href = path;
    return false;
}

function DoAdvancedSearch()
{
    var searchFor = document.getElementById( "searchFor").value;
    var searchUsing = document.getElementById( "searchUsingValue").value;
    var searchIn = document.getElementById( "searchInValue").value;
    var searchfilter;
    if ( document.getElementById( "forumValue") )
        searchFilter = document.getElementById( "forumValue").value;
    else
        searchFilter = document.getElementById( "searchFilter").value;
    var params = "../Home/Search.aspx?search=" + encodeURIComponent( searchFor ) + "&using=" + searchUsing + "&in=" + searchIn + "&ft=" + searchFilter + "&st=" + sortColumn + "&order=" + sortOrder;	
    var path = params;	
    //alert( path );
    location.href = path;
    return false;
}

function Sort( column, defaultOrder )
{
    if ( column == sortColumn )
    {
        if ( sortOrder == "desc" )
            sortOrder = "asc";
        else
            sortOrder = "desc";
    }
    else
    {
        sortColumn = column;
        sortOrder = defaultOrder;
    }

	GetSearchAsArray();
	var company = srchArray[ "company" ]; 

    var path = "../Home/Search.aspx?company=" + company + "&st=" + sortColumn + "&order=" + sortOrder;	
    //alert( path );
    location.href = path;
    return false;
 
}

function AddBookmark()
{
    var url = "http://www.uktvadverts.com";
    var title = "UK TV Adverts";
    
    if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, "");
    else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    } 
    else if(document.all)// ie
        window.external.AddFavorite(url, title);
    return false;
}

var ie5=document.all&&document.getElementById;
var ns6=document.getElementById&&!document.all;
var popupWindow = null;

function iecompattest(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function drag_drop(e)
{
	if (ie5&&dragapproved&&event.button==1)
	{
		popupWindow.style.left=tempx+event.clientX-offsetx+"px"
		popupWindow.style.top=tempy+event.clientY-offsety+"px"
	}
	else if (ns6&&dragapproved)
	{
		popupWindow.style.left=tempx+e.clientX-offsetx+"px"
		popupWindow.style.top=tempy+e.clientY-offsety+"px"
	}
	return false;
}

function stopdrag()
{
	dragapproved=false;
	document.onmousemove=null;
	document.onmouseup=null;
	//document.getElementById("popupContent").style.display="" //extra
}

function initializedrag(e)
{
	offsetx=ie5? event.clientX : e.clientX
	offsety=ie5? event.clientY : e.clientY
	//document.getElementById("popupContent").style.display="none" //extra
	tempx=parseInt(popupWindow.style.left)
	tempy=parseInt(popupWindow.style.top)

	dragapproved=true
	document.onmousemove=drag_drop
	document.onmouseup=stopdrag
}

function DisplayPopup(width,height,title,html)
{
	popupWindow = document.getElementById("popupWindow")
	popupWindow.style.width=(width+2)+"px"
	popupWindow.style.height=(height+20)+"px"
	var popupTitle = document.getElementById("popupTitleLeft")
	popupTitle.innerHTML = title;
	if ( popupWindow.style.display != 'block' )
	{
		//alert(document.body.clientWidth);
		popupWindow.style.left = ( ( document.body.clientWidth - width ) / 2 ) + "px"
		popupWindow.style.top=ns6? window.pageYOffset*1+130+"px" : iecompattest().scrollTop*1+130+"px"
	}
	
    /*var newdiv = document.createElement("div");
    newdiv.appendChild(document.createTextNode(html));
    var container = document.getElementById("popupContent");
    container.appendChild(newdiv);*/
	
	document.getElementById("popupContent").innerHTML = "<div>" + html + "</div>";
	//alert(html);
	popupWindow.style.display = 'block';
	//popupTitle.onmousedown = initializedrag;
	document.getElementById("popupTitleHolder").onmousedown = initializedrag;
}

function DisplayMedia( title, id, flags, url )
{
    var html = GetHTML( "../Adverts/Media.aspx?id=" + id + "&flags=" + flags + "&url=" + url );
    DisplayPopup(436,388,title,html);
    return false;
}

function HidePopup()
{
    if ( popupWindow != null )
    {
        popupWindow.style.display = 'none';
        document.getElementById("popupContent").innerHTML = "Loading...";
        popupWindow = null;
    }
    return false;
}

function XmlHttp() {}

XmlHttp.Create = function ()
{
	try
	{
		if (window.XMLHttpRequest)
		{
			var req = new XMLHttpRequest();

			//	Ensure that the readyState is supported
			if (req.readyState == null)
			{
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}

		if (window.ActiveXObject)
		{
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

function getXmlHttpPrefix()
{
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var tempObject;
	for (var i = 0; i < prefixes.length; i++)
	{
		try
		{
			tempObject = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

function GetHTML( href )
{
	var xmlHttp = XmlHttp.Create();
	try
	{
		//alert(href);
		xmlHttp.open("GET", href, false);
		xmlHttp.send(null);
		
		var html = xmlHttp.responseText;
		//alert(html);
		if ( html == null )
			html = "";
			
		return html;			
	}
	catch (e)
	{
		return href + "<br/>" + e.message + "<br><br>" + xmlHttp.responseText;
	}
	
	return null;
}
