
//*************************************
// Product Page Javascript
// Copyright: Nat Gale (nat.gale@yahoo.co.uk)
// Core Objects:
//  - Basket
//  - Scroller
//  - Modal
//  - Cookie
//  - Window Controller
//  - DOM Load
//*************************************

/*********************************************************
** Browser - to contain all required browser information
*********************************************************/

function BrowserBase()
{
    try
    {
        this.AgentName=navigator.userAgent.toLowerCase();
    }
    catch(e)
    {
        this.AgentName = '';
    }
    this.MajorVersionNumber =parseInt(navigator.appVersion);
    this.IsIE = ( this.AgentName.indexOf('msie') != -1 );
    this.IsChrome = ( this.AgentName.indexOf('chrome') != -1 );
    if ( this.IsIE )
    {
        this.Version = parseFloat(this.AgentName.substring(this.AgentName.indexOf('msie') + 5, this.AgentName.length));
    }
}
BrowserBase.prototype = {
    init: function()
    {
        if ( this.IsIE && this.Version < 7 )
        {
            //window.location = '/browser.shtml';
        }
    }
}
var Browser = new BrowserBase();

//*************************************
// Menu Object
//*************************************

function MenuBase()
{
    this.Initialised = false;
}
MenuBase.prototype = {
    init: function()
    {
        if ( !this.Initialised )
        {
			if ( document.getElementById('CategoryMenu') )
			{
				this.activateCategoryMenu();
			}
			this.Initialised = true;
		}
	},
	activateCategoryMenu: function()
	{
		var li = document.getElementById('CategoryMenu').getElementsByTagName('li');
		if ( li.length > 0 )
		{
			for ( var i = 0; i < li.length; i ++ )
			{
				li[i].onmouseover = function()
                {
                     this.className += ' Hover';
                }
                li[i].onmouseout = function()
                {
					if ( this.className.indexOf(' Hover') != -1 )
					{
	                    this.className = this.className.split(' Hover').join('');
					}
					else if ( this.className == 'Hover' )
					{
						this.className = '';
					}
                }
			}
		}
	}
}
var Menu = new MenuBase();

//*************************************
// Basket Object
//*************************************

function BasketBase()
{
    this.ID;
    this.Initialised = false;
}
BasketBase.prototype = {
    init: function()
    {
        if ( !this.Initialised )
        {
            // Get the cookie
            this.ID = Cookie.getValue('BASKETID');
            if ( this.ID == null )
            {
                // Set a new cookie
                var now = new Date();
                var val = now.getTime() + '-' + ip + '-' + ( Math.random() * 101 );
                Cookie.setValue('BASKETID', val );
            }
			
            // Get the cookie
            this.ID = Cookie.getValue('BASKETID');
            
			// Update the status
			this.updateStatus();
			
			// Prevent re-initialisation
            this.Initialised = true;
        }
    },
	updateStatus: function()
	{
		// If the basket panel exists and Cookies are enabled
		if ( document.getElementById('basketSummary') && ( this.ID != null ) )
		{
			// Get and update the basket values
			xmlhttpPost('/cgi/get_basket.cgi', this.ID );
		}
	}
}
var Basket = new BasketBase();

//*************************************
// Modal Object
//*************************************

function ModalBase()
{
    this.PopupDiv;
    this.PopupInnerDiv;
    this.BackgroundDiv;
    this.Initialised = false;
}
ModalBase.prototype = {
    init: function()
    {
        if ( !this.Initialised )
        {
            // Create the close bullet
            var a = document.createElement('a');
            a.href = 'javascript:Modal.close();';
            a.innerHTML = 'Close';
            var li = document.createElement('li');
            li.appendChild(a);
            var ul = document.createElement('ul');
            ul.appendChild(li);
            var menu = document.createElement('div');
            menu.className = 'Menu';
            menu.appendChild(ul);
            
            // Create the Inner Div
            this.PopupInnerDiv = document.createElement('div');
            this.PopupInnerDiv.className = 'Inner';
            
            // Create the Popup Div
            this.PopupDiv = document.createElement('div');
            this.PopupDiv.id = 'ModalPopup';
            this.PopupDiv.appendChild(menu);
            this.PopupDiv.appendChild(this.PopupInnerDiv);
            document.body.appendChild(this.PopupDiv);
			
            // Create the Background Div
            this.BackgroundDiv = document.createElement('div');
            this.BackgroundDiv.id = 'ModalBackground';
            document.body.appendChild(this.BackgroundDiv);
            
            // Whizz through the a tags to find any modal targets
            var at = document.getElementsByTagName('a');
            for ( var i = 0; i < at.length; i ++ )
            {
                if ( at[i].className == 'OpenModal' )
                {
					// Get the href and add the view arg
                    var h = at[i].href;
					h += ( h.indexOf('?') == -1 )? '?view=modal' : '&view=modal';
					
					// Re-write the href
                    at[i].setAttribute(
                        'href', 
                        'javascript:Modal.openIFrame("link' + i + '", "' + h + '", 600, 450);'
                    );
                }
            }
            
            // Flag as initialised
            this.Initialised = true;
        }
    },
    openIFrame: function( n, s, w, h ) // Name, Src, Width, Height
    {
        // Frame
        //var frame = document.createElement('iframe');
        //frame.width = w;
        //frame.height = h;
        //frame.frameBorder = "0";
        //frame.id = 'modalIFrame';
        //frame.name = name;
        //this.InnerDiv.appendChild( frame );
        
        // IFrame
        var frame = '<iframe id="ContactUsFrame" scrolling="auto" frameborder="0" marginwidth="0" marginheight="0"';
        frame += ' border="0" width="' + w + '" height="' + h + '" name="' + n + '" src="' + s + '">';
        frame += 'Please update your browser.</iframe>';

        // Insert the iframe
        this.PopupInnerDiv.innerHTML = frame;
        
        // Show the modal window
        this.show( w, h );
    },
    show: function( w, h )
    {
        // Move it down
        this.PopupDiv.style.top = '0';
        this.BackgroundDiv.style.top = '0';

        // Resize the window
        this.PopupDiv.style.width = ( w + 4 ) + 'px';
        this.PopupDiv.style.height = ( h + 2 ) + 'px';
        this.resize();
        
        // Register the window resize event
        WindowController.registerEvent('onresize','ResizeModal','Modal.resize()');
    },
    close: function()
    {
        // Resize the background
        this.BackgroundDiv.style.width = '1px';
        this.BackgroundDiv.style.height = '1px';
        this.BackgroundDiv.style.top = '-100px';
		
        // Move the Popup
        this.PopupDiv.style.width = '1px';
        this.PopupDiv.style.height = '1px';
        this.PopupDiv.style.top = '-100px';
		
        // Empty the Popup
        this.PopupInnerDiv.innerHTML = '';
		
		// Update the basket status
		Basket.updateStatus();
		
        // Unregister the window resize event
        WindowController.unregisterEvent('onresize','ResizeModal');
    },
    resize: function()
    {
        var b = { // Browser
            w: document.documentElement.clientWidth, 
            h: document.documentElement.clientHeight
        }
        var p = { // Popup
            w: this.PopupDiv.clientWidth,
            h: this.PopupDiv.clientHeight
        }

		var s = this.getBodyScroll();

        // Resize the background
        this.BackgroundDiv.style.width = b.w + 'px';
        this.BackgroundDiv.style.height = b.h + 'px';
		this.BackgroundDiv.style.left = s.x + 'px';
		this.BackgroundDiv.style.top = s.y + 'px';

		// Move the Popup
		this.PopupDiv.style.left = ((b.w / 2) - (p.w / 2) + s.x) + 'px';
		this.PopupDiv.style.top = ((b.h / 2) - (p.h / 2) + s.y) + 'px';
    },
	getBodyScroll: function() {
		var x = window.pageXOffset ||
            document.body.scrollLeft ||
            document.documentElement.scrollLeft;

		var y = window.pageYOffset ||
            document.body.scrollTop ||
            document.documentElement.scrollTop;

		return { x: (x ? x : 0), y: (y ? y : 0) };
	}
}

var Modal = new ModalBase();

//*************************************
// PostBack Object
//*************************************

function xmlhttpPost( urlStr, queryStr )
{
	var xmlHttpReq = false;

	// Figure out the required request type
	if ( window.XMLHttpRequest ) // Mozilla/Safari
	{
        xmlHttpReq = new XMLHttpRequest();
	}
	else if ( window.ActiveXObject ) // IE
	{
	    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	// Build the request.
	xmlHttpReq.open('POST', urlStr, true);
	xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
	// Define callback function, with nested function passed to this routine.
	xmlHttpReq.onreadystatechange = function()
	{
        if ( xmlHttpReq.readyState == 4 )
        {
            updatePage(xmlHttpReq.responseText);
        }
	}
	// Send the post request.
	xmlHttpReq.send(queryStr);
}

function updatePage( response )
{
    var data = eval( '(' + response + ')' );
    for ( var a in data )
    {
        if ( document.getElementById(a) )
        {
            var e = document.getElementById(a); // html 'e'lement
            var o = eval("data." + a ); // JSON sub 'o'bject
            if ( o.display ){ e.style.display = o.display; }
            if ( o.href ){ e.href = o.href; }
            if ( o.innerHTML ){ e.innerHTML = o.innerHTML; }
            if ( o.src ){ e.src = o.src; }
        }
    }
}

//*************************************
// Product List Object
//*************************************

function ProductListBase()
{
    this.Initialised = false;
}
ProductListBase.prototype = {
    init: function()
    {
        if ( !this.Initialised && document.getElementById('ProductList') )
        {
            // Activate the add to basket buttons
            this.activateButtons();
            
            this.activatePanels();
            
            this.Initialised = true;
        }
    },
    activatePanels: function()
    {
        var d = document.getElementById('ProductList').getElementsByTagName('div');
        for ( var i = 0; i < d.length; i ++ )
        {
            // If it's a product panel
            if ( d[i].className.indexOf('Product_') != -1 )
            {
                d[i].onmouseover = function()
                {
                    this.className += ' Hover';
                }
                d[i].onmouseout = function()
                {
                    this.className = this.className.split(' Hover').join('');
                }
                d[i].setAttribute('title','Click for details');
                d[i].onclick = function()
                {
					// Go the same link that the image has
					window.location = this.getElementsByTagName('a')[0].href;
                }
            }
        }
    },
    activateButtons: function()
    {
        var i = 1;
        var panels = true;
        while ( panels )
        {
            if ( document.getElementById('basketAddButton_' + i) )
            {
                var button = document.getElementById('basketAddButton_' + i);
				
				button.onmousedown = function()
                {
					// Get it's href and append the view arg
					var h = this.href;
					h += ( h.indexOf('?') == -1 )? '?view=modal' : '&view=modal';
					
					// Open the modal
                    Modal.openIFrame('basketFrame', h, 600, 450);
					
					// Cancel the click event
					return false;
                }
            }
            else
            {
                panels = false;
            }
            i ++;
        }

    }
}
var ProductList = new ProductListBase();

//*************************************
// Cookie Object
//*************************************

function CookieBase()
{
    this.Enabled = navigator.cookieEnabled;
}
CookieBase.prototype = {
    getValue: function(name)
    {
	    var arg = name + "=";
	    var alen = arg.length;
	    var clen = document.cookie.length;
	    var i = 0;
	    while (i < clen) {
		    var j = i + alen;
		    if (document.cookie.substring(i, j) == arg)
			    return this.getSubString(j);
			    i = document.cookie.indexOf(" ", i) + 1;
		    if (i == 0) break;
	    }
	    return null;
    },
    getSubString: function(offset)
    {
	    var endstr = document.cookie.indexOf (";", offset);
	    if (endstr == -1){ endstr = document.cookie.length; }
	    return unescape(document.cookie.substring(offset, endstr));
    },
    setValue: function(name, value)
    {
        if ( this.Enabled )
        {
	        var expires = new Date();
	        expires.setTime(expires.getTime() + (3600*24*60*60*1000));
	        var path = '/';
	        var domain = null;
	        var secure = false;
	        document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
        }
    }
}
var Cookie = new CookieBase();

//*************************************
// Window Controller Object
//*************************************

function WindowControllerBase()
{
    // Event Arrays - Arrays of {name, event} pairs
    this.ClickEvents = [];
    this.UnloadEvents = [];
    this.ResizeEvents = [];
    this.ClickTarget; // The element clicked on
}
WindowControllerBase.prototype =
{
    click: function(e)
    {
        // Get the window event for IE
        e = (!e) ? window.event : e;
        
        // Get the target
        this.ClickTarget = ( e.target )? e.target : e.srcElement;

        // Execute the events
        for ( var ce in this.ClickEvents )
        {
            eval( this.ClickEvents[ce].event );
        }
    },
    unload: function()
    {
        // Execute the events
        for ( var e in this.UnloadEvents )
        {
            eval( this.UnloadEvents[e].event );
        }
    },
    resized: function()
    {
        // Execute the events
        for ( var e in this.ResizeEvents )
        {
            eval( this.ResizeEvents[e].event );
        }
    },
    registerEvent: function(t, n, e) // Type, Name, Event
    {
        var replaced = false;
        var events = this.getEvent(t); // Get the events for this event type
        for (var ce in events)
        {
            if ( events[ce].name == n )
            {
                events[ce] = { name: n, event: e };
                replaced = true;
                break;
            }
        }
        if ( !replaced )
        {
            events.push({ name: n, event: e });
        }
    },
    unregisterEvent: function(t, n) // Type, Name
    {
        var events = this.getEvent(t); // Get the events for this event type
        for (var ce in events)
        {
            if ( events[ce].name == n )
            {
                delete events[ce];
                break;
            }
        }
    },
    getEvent: function(t)
    {
        switch(t)
        {
            case 'click':
                return this.ClickEvents;
                break;
            case 'unload':
                return this.UnloadEvents;
                break;
            case 'onresize':
                return this.ResizeEvents;
                break;
        }
    },
    getClickTarget: function()
    {
        return this.ClickTarget;
    }
}
var WindowController = new WindowControllerBase();

document.onmousedown = function(e)
{
    WindowController.click(e);
}
window.onunload = function()
{
    WindowController.unload();
}
window.onresize = function()
{
    WindowController.resized();
}
window.onscroll = function()
{
    WindowController.resized();
}

//*************************************
// Analytics
//*************************************

function AnalyticsBase()
{
    this.Initialised = false;
}
AnalyticsBase.prototype =
{
	init: function()
	{
		if ( ( typeof eventTrackingOn != 'undefined' ) && eventTrackingOn && !this.Initialised )
		{
			var a = document.getElementsByTagName('a');
			for ( var i = 0; i < a.length; i ++ )
			{
				if ( a[i].className.indexOf('TrackEvent-') != -1 )
				{
					a[i].onclick = function()
					{
						Analytics.trackEvent( this.className );
					}
				}
			}
			this.Initialised = true;
		}
	},
    trackEvent: function( className )
    {
		// Get the args in the class name
		var args = className;
		
		// If we have multiple classes, then find the required one
		if ( className.indexOf(' ') != -1 )
		{
			var cls = className.split(' ');
			for ( var i = 0; i < cls.length; i ++ )
			{
				if ( cls[i].indexOf('TrackEvent-') != -1 )
				{
					args = cls[i];
					break;
				}
			}
		}
		
		// Split out the args in the class name: 1 - category, 2 - action, 3 - label
		args = args.split('-');
		
		// alert( 'pageTracker._trackEvent("' + args[1] + '", "' + args[2] + '", "' + args[3] + '"' );
        try
        {
			_gaq.push(['_trackEvent', args[1], args[2], args[3]]);
			
            // var pageTrackerResponse = pageTracker._trackEvent(args[1], args[2], args[3], '');
        }
        catch (err) { }
    }
}

var Analytics = new AnalyticsBase();

//*************************************
// DOM Load
//*************************************

function domFunction (f, a)
{
    var n = 0;
 	var t = setInterval( function()
        {
            var c = true;
            n++;
            if ( typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
            {
                c = false;
                if (typeof a == 'object')
                {
                    for ( var i in a )
                    {
                        if ((a[i] == 'id' && document.getElementById(i) == null) || (a[i] == 'tag' && document.getElementsByTagName(i).length < 1))
                        {
                            c = true;
                            break;
                        }
                    }
                }
                if (!c) { f(); clearInterval(t); }
            }
            if (n >= 60) { clearInterval(t); }
        }, 250 );
}

// Detect when the DOM has loaded
var dom_load = new domFunction( function()
    {
        Browser.init();
		Menu.init();
        Modal.init();
        Basket.init();
        ProductList.init();
		Analytics.init();
    }, { 'dom_loaded' : 'id' }); // Once the last div has been detected

function popup( win, w, h )
{
    if ( window.pop ){ window.pop.close(); } // close an open one
    if ( popup.arguments.length < 2 ){ w = 540; };
    if ( popup.arguments.length < 3 ){ h = 440; };
    var args = 'toolbar=no,location=no,directories=no,status=yes,scrollbars=yes,resizable=yes,copyhistory=no,locationbar=no,width=';
    args += w + ',height=' + h + ',screenX=0,screenY=0,top=0,left=0';
    pop = window.open( win, 'ccpopup', args );
}

