function e$( id ) { return document.getElementById( id ); }
function c$( className ) { return document.getElementsByClassName( className ); }
function t$( tagName ) { return document.getElementsByTagName( tagName ); }

Utility = 
{
	//initialises the entire page
	initPage:function()
	{
		//initialise the login window
		LoginWindow.infoId = "accountInfo";
		LoginWindow.loginButtonId = "ctl00_LoginWindow_loginButton";
		LoginWindow.loginButtonIdAlt = "ctl01_LoginWindow_loginButton";
		LoginWindow.logoutLinkId = "logoutLink";
		LoginWindow.boxId = "loginWindow";
		LoginWindow.onId = "loginOn";
		LoginWindow.offId = "loginOff";
		LoginWindow.loginErrorId = "loginError";
		LoginWindow.showLoginButtonId = "closedTitle";
		LoginWindow.hideLoginButtonId = "openTitle";
		LoginWindow.init();
	},

	//page click handlers
	clickHandler:function(e)
	{
		/*
		var target = Utility.getClickTarget(e);
		var retVal = true;

		// if the target of the click is an excepted invoker then always return true
		if (Presentation.cssClassExists(target,"exceptedInvoker"))
		    return true;
		
		if (!AlertWindow.toggle(e, target)) retVal = false;
		
		//IE FIX: if the target has an onclick event then ALWAYS return false
		if (target.onclick)
		    retVal = false;
		    
		return retVal;
		*/
	},
	
	//calculates the top left position of the given element
	getElementPosition:function(elm)
	{
		var oleft = otop = 0;
		if (elm.offsetParent) {
			do {
				oleft += elm.offsetLeft;
				otop += elm.offsetTop;
			} while (elm = elm.offsetParent);
		}
		return [otop,oleft];
	},
	
	//gets the target of the given event
	getClickTarget:function(ev)
	{
		var target;
		if (!ev) ev = window.event;
		if (ev.target)
			target=ev.target;
		else if (ev.srcElement)
			target=ev.srcElement;
		if (target.nodeType==3) // defeat Safari bug
			target = target.parentNode;
		return target;
	},
	
	//shows given element at given position
	showElement:function(elm,posTop,posLeft)
	{
		elm.style.left = posLeft + "px";
		elm.style.top = posTop + "px";
		elm.style.display = "block";
	},
	
	//resets given element to 0,0 and hides it
	hideElement:function(elm)
	{
		elm.style.left = 0 + "px";
		elm.style.top = 0 + "px";
		elm.style.display = "none";
	},
	
	//gets the first ancestor of given element that contains given class name, otherwise returns false
	getAncestorWithCssClass:function(elm, className)
	{
		//if the clicked element IS the switch return the element
		if(Presentation.cssClassExists(elm, className)) return elm;
		
		//if the parent node doesnt exist then return false
		if (!elm.parentNode) return false;
		
		do {
			if (Presentation.cssClassExists(elm, className))
				return elm;
			
		} while (elm = elm.parentNode);
		
		return false;
	},
	
	//retruns a unique number used in ajax queries to trick browsers not to cache
	getUniqueStamp:function()
	{
	    return new Number(Math.round(Math.random() * Math.pow(2,24)));
	}
}

Presentation = 
{
	//checks if the given css class exists in the class string of the element
	cssClassExists:function(element, className)
	{
		if (!element.className) return false;
		var classes = element.className.split(' ');
		for (var i = 0; i < classes.length; i++)
		{
			if (classes[i] == className) return true;
		}
		return false;
	},
	
	//adds a class name to the given elements classname property without destroying existing classes
	addCssClass:function(element, className)
	{
		if(!element) return;
		if (Presentation.cssClassExists(element, className)) return;
		element.className += element.className ? ' ' + className : className;
	},
	
	//removes the given class name from the given element without destroying current classes
	removeCssClass:function(element, className)
	{
		if(!element) return;
		if (!Presentation.cssClassExists(element, className)) return;
		
		var rep;
		if (element.className.match(' ' + className))
			rep = ' ' + className;
		else if (element.className.match(className + ' '))
			rep = className + ' ';
		else
			rep = className;

		element.className = element.className.replace(rep, '');
	}
}

AlertWindow = 
{
	// variables 
	box:null,
	boxId:"",
	visible:false,	
	toggleSwitch:"",
	toggleElement:null,
	toggleSwitchOff:"",
	alertToggleElement:null,

	//initialises the login window
	init:function()
	{
		if (!document.getElementById) return;
		AlertWindow.box = e$(AlertWindow.boxId);
		if (!AlertWindow.box) return;
		//make sure that the login window is absolutely positioned
		AlertWindow.box.style.position = "absolute";
		AlertWindow.alertToggleElement = e$("ctl00_MasterHolder_searchResults_AlertControl_buttonSaveAlert");
		if (AlertWindow.alertToggleElement) 
		{
		    if (LoginWindow.userIsLoggedIn) AlertWindow.alertToggleElement.onclick = function(){ return AlertWindow.saveAjaxAlert() };
		    else AlertWindow.alertToggleElement.onclick = AlertWindow.toggle;
		}
	},
	
	//toggles the login window on or off
	toggle:function(e)
	{
		if (!AlertWindow.box)
			return true;
		
		var target = Utility.getClickTarget(e);

		//find out if this element or one of its ancestors is a toggle switch
		AlertWindow.toggleElement = Utility.getAncestorWithCssClass(target, AlertWindow.toggleSwitch);

		//if its not a toggleable element then hide the window and return
		if (!AlertWindow.toggleElement) 
		{
			AlertWindow.hide();
			return true;
		}
		
		if (!AlertWindow.visible) AlertWindow.show(Utility.getElementPosition(AlertWindow.toggleElement));
		else return AlertWindow.hide();
		
		return false;
	},
	
	//shows the login window at required position
	show:function(pos)
	{
		Utility.showElement(AlertWindow.box, pos[0] + 4 + AlertWindow.toggleElement.offsetHeight, pos[1])
		AlertWindow.visible = true;
	},
	
	//resets the position to 0,0 and hides the login window
	hide:function()
	{
		//check that the click didnt happen inside the loginWindow
		if (AlertWindow.toggleElement == AlertWindow.box) return true;
		Utility.hideElement(AlertWindow.box) 
		AlertWindow.visible = false;
		return false;
	},
    
    //does an async save alert
	saveAjaxAlert:function()
	{
        //read email and section from input fields and send as post
        var email = e$("ctl00_AlertWindow_alertEmail").value;
        var section = e$("alertSiteSection").value;
        //new Ajax("/AjaxAlert.aspx" + window.location.search, {method: 'post', onComplete: AlertWindow.saveAjaxAlertComplete, onFailure: AlertWindow.saveAjaxAlertError, postBody: 'em='+email+'&s='+section}).request();
        $.ajax({
            type: 'POST',
            url: '/AjaxAlert.aspx' + window.location.search,
            data: 'em='+email+'&s='+section,
            dataType: 'json',
            success: function(data){ AlertWindow.saveAjaxAlertComplete(data); },
            error: AlertWindow.saveAjaxAlertError
        });
        return false;
	},	
	
	//handles completed save alert attempt
	saveAjaxAlertComplete:function(jsonResponse)
	{
        var response = jsonResponse; //Json.evaluate(jsonResponse);
        if (response[0].saved == "True")
        {
            var saveAlertButton = e$("ctl00_MasterHolder_searchResults_AlertControl_buttonSaveAlert");
            var alertLabel = e$("alertWindowLabel");
            alertLabel.removeChild(alertLabel.firstChild);
            saveAlertButton.value = "Alert Saved!";
            saveAlertButton.onclick = null;
            saveAlertButton.disabled = true;
            AlertWindow.toggleElement = saveAlertButton.parentNode;
            AlertWindow.hide();
            //remove toggle off of alert windows
            var alertToggles = c$(AlertWindow.toggleSwitch);
            for (i = 0; i < alertToggles.length; i++)
            {
                alertToggles[i].className = AlertWindow.toggleSwitchOff;
            }
        }
        else
        {
            //display feedback
            alert("Saving alert failed!");
        }
	},
		
	//handles failed save alert attempt
	saveAjaxAlertError:function(e)
	{
        e$("ctl00_AlertWindow_Save").onclick = null;	    
        e$("ctl00_AlertWindow_Save").click();	    
	}
}

LoginWindow = 
{
	// variables 
	box:null,
	boxId:"",
	info:null,
	infoId:"",
	loginButton:null,
	loginButtonId:"",
	loginButtonIdAlt:"",
	logoutLink:null,
	logoutLinkId:"",
	userIsLoggedIn:false,
	on:null,
	onId:"",
	off:null,
	offId:"",
	loginError:null,
	loginErrorId:"",
	showLoginButton:null,
	showLoginButtonId:"",
	hideLoginButton:null,
	hideLoginButtonId:"",
	forgotPWLink:null,

	//initialises the login window
	init:function()
	{
		if (!document.getElementById) return;
		LoginWindow.box = e$(LoginWindow.boxId);
		LoginWindow.info = e$(LoginWindow.infoId);
		LoginWindow.loginButton = e$(LoginWindow.loginButtonId);
		LoginWindow.loginError = e$(LoginWindow.loginErrorId);

		if (!LoginWindow.loginButton) LoginWindow.loginButton = e$(LoginWindow.loginButtonIdAlt);
		LoginWindow.logoutLink = e$(LoginWindow.logoutLinkId);
		
		if (!LoginWindow.loginButton && !LoginWindow.logoutLink) return;
		
		LoginWindow.loginButton.onclick = LoginWindow.doAjaxLogin;
		LoginWindow.logoutLink.onclick = LoginWindow.doAjaxLogout;
		
		LoginWindow.userIsLoggedIn = Presentation.cssClassExists(LoginWindow.box, "hidden");
		
		LoginWindow.forgotPWLink = e$("forgotPW");
		LoginWindow.forgotPWLink.onclick = LoginWindow.handleForgottenPassword;

	},
	
	initShowHide:function()
	{
		LoginWindow.onId = "loginOn";
		LoginWindow.offId = "loginOff";
		LoginWindow.showLoginButtonId = "closedTitle";
		LoginWindow.hideLoginButtonId = "openTitle";
		LoginWindow.on = e$( LoginWindow.onId );
		LoginWindow.off = e$( LoginWindow.offId );
		LoginWindow.showLoginButton = e$( LoginWindow.showLoginButtonId );
		LoginWindow.hideLoginButton = e$( LoginWindow.hideLoginButtonId );
		
		if (LoginWindow.showLoginButton)
		{
			LoginWindow.showLoginButton.onclick = LoginWindow.openLoginWindow;
		}
		
		if (LoginWindow.hideLoginButton)
		{
			LoginWindow.hideLoginButton.onclick = LoginWindow.hideLoginWindow;
		}
	},
	
	//does an async log in of the user
	doAjaxLogin:function()
	{
	    LoginWindow.hideLoginError();
	    	
        //read uname, pw and rememberme from input fields and send as post
        var uname = (e$("ctl00_LoginWindow_loginEmail")) ? e$("ctl00_LoginWindow_loginEmail").value : e$("ctl00_LoginWindow_loginEmail").value;
        var pword = (e$("ctl00_LoginWindow_loginPassword")) ? e$("ctl00_LoginWindow_loginPassword").value : e$("ctl00_LoginWindow_loginPassword").value;
        var remme = (e$("ctl00_LoginWindow_loginRemember")) ? e$("ctl00_LoginWindow_loginRemember").value : e$("ctl00_LoginWindow_loginRemember").value;
        //new Ajax("/AjaxLogin.aspx", {method: 'post', onComplete: LoginWindow.ajaxLoginComplete, onFailure: LoginWindow.ajaxLoginError, postBody: 'un='+uname+'&pw='+pword+'&r='+remme}).request();
        $.ajax ({ 
                    url: '/AjaxLogin.aspx', 
                    type: 'POST',
                    dataType: 'json',
                    data: 'un='+uname+'&pw='+pword+'&r='+remme,                
                    success: function(data){ LoginWindow.ajaxLoginComplete(data); }, 
                    error: LoginWindow.ajaxLoginError 
                });
        return false;
	},	
	
	//handles completed login attempt
	ajaxLoginComplete:function(jsonResponse)
	{
        if (!LoginWindow.box || !LoginWindow.info) return;
        var response = jsonResponse;//Json.evaluate(jsonResponse);
        if (response[0].loggedin == "True")
        {
			//make login window invisible and account window visible
			Presentation.addCssClass(LoginWindow.box, "hidden");
			Presentation.removeCssClass(LoginWindow.info, "hidden");
			
			// change alert events
            if (AlertWindow.alertToggleElement) AlertWindow.alertToggleElement.onclick = function() { return AlertWindow.saveAjaxAlert(); };            
            Presentation.addCssClass(AlertWindow.alertToggleElement, "ajaxInvoker");
            //remove toggle off of alert windows
            var alertToggles = c$(AlertWindow.toggleSwitch);
            for (i = 0; i < alertToggles.length; i++)
            {
                alertToggles[i].className = AlertWindow.toggleSwitchOff;
            }
            LoginWindow.userIsLoggedIn = true;
		}
        else
        {
            LoginWindow.userIsLoggedIn = false;
            // display error message to user
            LoginWindow.displayLoginError();
        }
	},
		
	//handles failed login attempt
	ajaxLoginError:function(e)
	{
        if (!LoginWindow.loginButton) return;
        LoginWindow.loginButton.onclick = null;	    
        LoginWindow.loginButton.click();	    
	},
	
	//does an async log out of the user
	doAjaxLogout:function()
	{
        //new Ajax("/AjaxLogin.aspx", {method: 'post', onComplete: LoginWindow.ajaxLogoutComplete, onFailure: LoginWindow.ajaxLogoutError, postBody: 'l=true'}).request();
        $.ajax ({ 
                    url: '/AjaxLogin.aspx', 
                    type: 'POST',
                    dataType: 'json',
                    data: 'l=true',                
                    success: function(data){ LoginWindow.ajaxLogoutComplete(data); }, 
                    error: LoginWindow.ajaxLogoutError 
                });
        return false;
	},	
	
	//handles completed logout attempt
	ajaxLogoutComplete:function(jsonResponse)
	{
		//make login window visible and account window invisible
		Presentation.addCssClass(LoginWindow.info, "hidden");
		Presentation.removeCssClass(LoginWindow.box, "hidden");
		//detach events from alerts
        if (AlertWindow.alertToggleElement) AlertWindow.alertToggleElement.onclick = AlertWindow.toggle;            
        Presentation.removeCssClass(AlertWindow.alertToggleElement, "ajaxInvoker");
        //attach toggle off of alert windows
        var alertToggles = c$(AlertWindow.toggleSwitchOff);
        for (i = 0; i < alertToggles.length; i++)
        {
            alertToggles[i].className = AlertWindow.toggleSwitch;
        }
        LoginWindow.userIsLoggedIn = false;
	},
		
	//handles failed logout attempt
	ajaxLoginError:function(e)
	{
        window.location.href = "/AjaxLogin.aspx?l=true";
	},
	
	openLoginWindow:function()
	{
		LoginWindow.on.style.display = 'block';
		LoginWindow.off.style.display = 'none';
		return false;
	},
	
	hideLoginWindow:function()
	{
		LoginWindow.off.style.display = 'block';
		LoginWindow.on.style.display = 'none';
		return false;
	},
	
	displayLoginError:function()
	{
		LoginWindow.loginError.style.display = 'block';
		LoginWindow.loginError.innerHTML = 'Login Failed!';
	},
	
	hideLoginError:function()
	{
		LoginWindow.loginError.style.display = 'none';
		LoginWindow.loginError.innerHTML = '';
	},	
	
	handleForgottenPassword:function()
	{
	    if (e$("ctl00_LoginWindow_loginEmail") && e$("ctl00_LoginWindow_loginEmail").value.length > 0)
	    LoginWindow.forgotPWLink.href = LoginWindow.forgotPWLink.href + "?e=" + e$("ctl00_LoginWindow_loginEmail").value;
	}

}

MotorWebWindow = 
{
	// Variables
	url:"",
	emailId:"",
	email:null,
	purchaseButtonId:"",
	purchaseButton:null,
	
	init:function()
	{
		if (!document.getElementById) return;
		MotorWebWindow.email = e$( MotorWebWindow.emailId );
		MotorWebWindow.purchaseButton = e$( MotorWebWindow.purchaseButtonId );
		
		if ( MotorWebWindow.purchaseButton )
		{
			MotorWebWindow.purchaseButton.onclick = function(){ return MotorWebWindow.openPaymentWindow() };
		}
	},
	
	openPaymentWindow:function()
	{
		Page_ClientValidate( 'MotorWeb' );
	
		if ( Page_IsValid && MotorWebWindow.url != "" )
		{
			var url = MotorWebWindow.url + "&email=" + MotorWebWindow.email.value;
		
			window.open( url, "motorweb", "status=1,toolbar=0,location=0,menubar=1,directories=0,resizable=1,scrollbars=1,height=640,width=1040" );
		}

		return false;
	}
}

function DirectorySearchWindow( whatId ) 
{
	// variables
	var what = null;
	
	this.initSearchWindow = function() 
	{
		what = e$( whatId );
		
		what.value = "What";
		what.style.color = "#999";
		what.onfocus = this.enterTextBox;
		what.onblur = this.exitTextBox;
	}
	
	this.enterTextBox = function()
	{
		if ( what.value == "What" )
		{
			what.value = "";
			what.style.color = "#000";
		}
	}
	
	this.exitTextBox = function()
	{
		if (what.value == "" )
		{
			what.value = "What";
			what.style.color = "#999";
		}
	}
}

document.getElementsByClassName = function(cssClass)
{
	var allElements = document.all ? document.all : t$('*');
	var retElements = new Array();
    for(var i=0; i<allElements.length; i++){
        if(Presentation.cssClassExists(allElements[i], cssClass))
            retElements.push(allElements[i]);
    }
    return (retElements);
}

window.onload = Utility.initPage;