var abc = 0;
if (typeof LookCorp == 'undefined') var LookCorp = {}; // Make sure the base namespace exists.

/* Error reporting */
LookCorp.reportError = function(errorMsg, source, line) {
    var baseDir = SizeSwitcher.baseDir;
    if (!baseDir) baseDir = '/controls/';
    var url = baseDir + "JsErrorReport.ashx?";
    url += "page=" + encodeURIComponent(document.location);
    url += "&msg=" + encodeURIComponent(errorMsg);
    if (source) url += "&source=" + encodeURIComponent(source);
    if (line) url += "&line=" + encodeURIComponent(line);
    url += "&ts=" + encodeURIComponent(new Date().getTime());
    
    var img = new Image();
    img.src = url;
};

// Report unhandled exceptions
window.onerror = function(msg, url, line) {
    LookCorp.reportError(msg, url, line);
};

// Report jquery ajax errors
$("body").ajaxError(function(event, request, settings) {
    if (settings.url.indexOf('.gif') > 0) return;
    LookCorp.reportError("Error " + request.status + " - " + request.statusText, settings.url);
});

// Report anthem errors
window.Anthem_Error = function(result) {
    LookCorp.reportError(result.error + " " + result.responseText);
};

/*** Common functions ***/
if (typeof $id == 'undefined') {
    window.$id = function(element) {
        if (typeof element == 'string') {
            return document.getElementById(element);
        } else {
            return element;
        }
    };
}

// Anthem calls this whenever it finishes a callback
function Anthem_PostCallBack() {
    // Notify the popup quotes that a callback has happened, in case they need to redraw after a page reflow
    LookCorp.PopupQuote.onCallback();
}

/* slightly modified version so the viewstate isn't sent / recieved
   otherwise copied from Anthem_InvokeControlMethod
 */
function Anthem_InvokeControlMethodStateless(id, methodName, args, clientCallBack, clientCallBackArg) {
    Anthem_Clear__EVENTTARGET(); // fix for bug #1429412
    return Anthem_CallBack(null, "Control", id, methodName, args, clientCallBack, clientCallBackArg, false, false);
};

// add a function to be called at window.onload (can be called multiple times)
LookCorp.addLoadEvent = function(func){
	var oldonload = window.onload;
	
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
};

LookCorp._registeredListeners = []; /* List of attached event listeners so that onunload can remove them to stop ie memory leaks */

// adds an event listener in a cross browser way (also stores the event handler so it can be unattached for ie memory leaks)
LookCorp.attachEventListener = function(instance, eventName, listener) {
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        };
        instance.attachEvent("on" + eventName, listenerFn);
    } else {
        // Event registration not supported
    }
    var evt = {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
    LookCorp._registeredListeners.push(evt);
    return evt;
};

LookCorp.removeEventListener = function(evt) {
    var instance = evt.instance;
    if (instance) {
        if (instance.removeEventListener) {
            instance.removeEventListener(evt.name, evt.listener, false);
        } else if (instance.detachEvent) {
            instance.detachEvent("on" + evt.name, evt.listener);
        }
    }
    for (var i = 0; i < LookCorp._registeredListeners.length; i++) {
        if (LookCorp._registeredListeners[i] == evt) {
            LookCorp._registeredListeners.splice(i, 1);
            break;
        }
    }
};

// Called on page unload to unregister any event handlers
LookCorp.unregisterAllEvents = function() {
    while (LookCorp._registeredListeners.length > 0) {
        LookCorp.removeEventListener(LookCorp._registeredListeners[0]);
    }
};

// Help window popup
LookCorp.popHelp = function(linkElement, width, height) {
    linkElement.blur();

    var re = /[^\d\w]/g; // regex to match non-alpha and non-numeric (they are replaced with _ for the window id, since weird characters cause problems)
    var url = linkElement.href;
    var id = url.replace(re, '_');
    var screenWidth = self.screen.width;
    var screenHeight = self.screen.height;
    width = width || (screenWidth / 2.2); // default width is 45% of screen width
    height = height || (screenHeight * (2/3)); // default height is 2/3 screen height
    
    width *= SizeSwitcher.getCurrentRatio();
   
    var top = screenHeight / 12; // place top 1/12th from top of screen
    var left = (screenWidth * (11/12)) - width; // place 1/12th from right of screen
    var ref = window.open(url, id, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=' + width + ',height=' + height + ',screenX=' + left + ',left=' + left + ',screenY=' + top + ',top=' + top);
    
    if (ref) {
        ref.focus();
    }
    
    return false;
};

LookCorp.popHelpSmall = function(linkElement, width, height) {
    width = width || (self.screen.width / 3); // default width is 1/3 of screen width
    height = height || (self.screen.width / 4); // default height is 1/4 of screen height
    return LookCorp.popHelp(linkElement, width, height);
};

// fullscreen popup
LookCorp.popWindow = function(linkElement)
{
    linkElement.blur();

    var url = linkElement.href;
    var ref = window.open(url, '_blank');
    
    if (ref) {
        ref.focus();
    }
    
    return false;
};

// Hides an element, superceded by jquery's hide
LookCorp.hide = function(element) {
    element.style.display = 'none';
};

// Shows an element, superceded by jquery's show
LookCorp.show = function(element) {
    element.style.display = '';
};

LookCorp.getPosition = function(element) // find the position of an element relative to the top left of window
{
    var x = 0, y = 0;
    do {
        x += element.offsetLeft;
		y += element.offsetTop;
        element = element.offsetParent;
    } while (element);
    return {'x': x, 'y': y};
};

// Find out which element triggered the event
LookCorp.getEventTarget = function(ev)
{
    var element = ev; // Default element to whatever was passed in. If an element is passed instead of an event object, the element will still be returned
    if (ev.target) element = ev.target;
    if (ev.srcElement) element = ev.srcElement;
    if (element.nodeType == 3) element=element.parentNode; // defeat Safari bug
	return element;
};

// Get the text content of an element (must only have text, no html tags)
LookCorp.getElementText = function(element) {
    if (element.childNodes.length != 1 || element.childNodes[0].nodeType != 3) { // 3: text node
        return null;
    }
    return element.childNodes[0].nodeValue;
};

// Sets the text content of an element (must only have text, no html tags)
LookCorp.setElementText = function(element, text) {
    if (element.childNodes.length == 0) {
        var textNode = document.createTextNode(text);
        element.appendChild(textNode);
    } else if (element.childNodes.length != 1 || element.childNodes[0].nodeType != 3) { // 3: text node
        return;
    }
    element.childNodes[0].nodeValue = text;
};

LookCorp.isChild = function(c,p) { // Check if c is a child of p in the dom
    while(c) {
	    if (c == p) 
		    return true;
	    c = c.parentNode;
    }
    return false;
};

// Brings up the browser's print dialog
LookCorp.printPage = function(element) {
    if (element) {
        element.blur();
    }
    if (window.print) {
        window.print();
    } else {
        alert("Sorry, your browser doesn't support printing this way.\n" + 
            "Try choosing Print from the File menu.");
    }
    
    return false;
};

// Closes the window (used for popups)
LookCorp.closeWindow = function(element) {
    window.close();
    
    if (window.opener) {
        window.opener.focus();
    }
    
    return false;
};

// Performs a .Net String.Format style substitution
LookCorp.substitute = function(str) {
    for (var i = 1; i < arguments.length; i++) {
        str = str.replace("{" + (i - 1) + "}", arguments[i]);
    }
    return str;
};

// Trim leading and trailing white space from a string
LookCorp.trimString = function(str) {
  str = str.replace( /^\s+/g, "" );
  return str.replace( /\s+$/g, "" );
};

// Parse date of format dd[/-.]mm[/-.][yy]yy only, otherwise returns null
LookCorp.parseDate = function(dateStr) {
    try {
        if (!dateStr || typeof(dateStr) != "string") return null;
        
        // Try to split the date by '/', '-', and '.'
        var dateStrArray = dateStr.split('/');
        if (dateStrArray.length != 3)
        {
            dateStrArray = dateStr.split('-');
            if (dateStrArray.length != 3)
            {
                dateStrArray = dateStr.split('.');
                if (dateStrArray.length != 3)
                    return null;
            }
        }
        
        var d = parseInt(dateStrArray[0], 10), m = parseInt(dateStrArray[1], 10), y = parseInt(dateStrArray[2], 10);
        if (y < 38) y += 2000; // Don't bother with ancient dates
        var date = new Date(y, (m - 1), d); // javascript months are 0 indexed
        
        // Sanity checks (if any of d,m,y are out of range, they'll be adjusted in the date object)
        if (d != date.getDate() || (m - 1) != date.getMonth() || y != LookCorp.getDateYear(date)) return null;
        
        return date;
    } catch (e) {
        return null;
    }
};
// Works around inconsistent browser handling of 2 digit years
LookCorp.getDateYear = function(date) {
    var year = date.getYear();
	year %= 100; // get last 2 digits of year
	year += (year < 38) ? 2000 : 1900; // 2038 is max date in javascript
	return year;
};

// validates a date of the exact format d/m/yyyy
LookCorp.validateDate = function(source, args) {
    args.IsValid = LookCorp.parseDate(args.Value) != null;
    return args.IsValid;
};

// Client side script for checkbox validator
// called by CheckboxValidator
checkboxValidatorEvaluateIsValid = function(val)
{
    var control = $id(val.controltovalidate);
    var mustBeChecked = (val.mustBeChecked == "true");
    
    return control.checked == mustBeChecked;
};

// Gets the selected value from a group of radio buttons
LookCorp.getRadioValue = function(inputName) {
    var foundRadio = $("input[name=" + inputName + "]:checked");
    if (foundRadio.length == 0) {
        return null;
    } else {
        return foundRadio.val();
    }
};

// Selects one radio button from a group given the value
LookCorp.setRadioChecked = function(inputName, value) {
    var foundRadio = $("input[name=" + inputName + "][@value=" + value + "]");
    if (foundRadio.length > 1) {
        foundRadio.each(function(index) {
            this.checked = true;
        });
    }
};

// Change the radio button styles when selection is changed
LookCorp.setRadioStyle = function(spanName) {
    var foundRadio = $("span#" + spanName + " input");
    if (foundRadio.length > 1) {
        foundRadio.each(function(index) {
            var label = this.nextSibling;
            if (label && (label.tagName.toLowerCase() == "label")) {
                label.className = (this.checked) ? "selected" : "";
            }
        });
    }        
    return true;
};

// to avoid hardcoding, use this for any gst calculations
LookCorp.gstRate = 0.10;

// validates a credit card no.
LookCorp.validateCC = function(ccNum) {
    var checksum = 0;
    var factor = 0;
    
    // do checksum validation on credit card number
    if (ccNum.length < 16) {
        return false;
    }
    
    factor = (ccNum.length % 2 != 0) ? 1 : 2;
  
    for (var x = 0; x < ccNum.length; x++) {
        var digit = ccnum.charAt(x);

        if (digit * factor > 9) {
            checksum += (digit * factor) - 9;
        } else {
            checksum += digit * factor;
        }

        factor = (factor % 2) + 1;
    }

    if(checksum % 10 != 0) {
        return false;
    }
    
    // VISA is 4xxx xxxx xxxx xxxx
    // MC is 5{0-5}xx xxxx xxxx xxxx
    // BC is 56xx xxxx xxxx xxxx
    //if ((ccnum.charAt(0)) == 4 || (ccnum.charAt(0)) == 5) {
    //    args.IsValid = true;
    //} else {
    //    args.IsValid = false;
    //}   
    return true;
};

LookCorp.abnCheckDigitWeights = new Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);

LookCorp.validateABN = function(abnNum) {
  
    if ((abnNum.length != 11) || (abnNum.charAt(0) == '0')) {
        return false;
    }

    var checksum = LookCorp.abnCheckDigitWeights[0] * (abnNum.charAt(0) - 1);

    for (var x = 1; x < 11; x++)
        checksum += (LookCorp.abnCheckDigitWeights[x] * abnNum.charAt(x));

    return ((checksum != 0) && (checksum % 89 == 0));
};

// Raises an event on an element as the browser would
LookCorp.raiseEvent = function(eventType, element) {
    //On IE
    if(element.fireEvent)
    {
        element.fireEvent('on' + eventType);
    }
    //On Gecko based browsers
    if(document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        if(evt.initEvent)
        {
            evt.initEvent(eventType, true, true);
        }
        if(element.dispatchEvent)
        {
            element.dispatchEvent(evt);
        }
    }
};

$(function() {
    // Attach search event handlers
    var searchBox = $('.search input');
    searchBox.keydown(LookCorp.searchBoxKeyDown);
    searchBox.focus(function() {
         var searchBox = $(this);
         if (searchBox.hasClass("empty")) {
             searchBox.val("");
             searchBox.removeClass("empty");
         }
    });
    searchBox.blur(function() {
        var searchBox = $(this);
        if (searchBox.val() == "") {
            searchBox.val("Search...");
            searchBox.addClass("empty");
        }
    });
});

LookCorp.searchBoxKeyDown = function(event) {
    if (!event) return;
    
    if (event.keyCode == 13) { // return key
        var goButton = this.parentNode.getElementsByTagName('a')[0];
        window.location = goButton.href;
        event.preventDefault();
        //event.stopPropagation();
    }
};

// Attach unregister event to handle ie memory leaks
LookCorp.attachEventListener(window, 'unload', LookCorp.unregisterAllEvents);

/* Submenu click handler */
LookCorp.submenuTimeout = null;
$(function() { // This function will run onload
    // Mouse version
    $('#navMenu li.autoOpen').mouseover(
        function() {
            // If there's an existing timeout set, clear it
            if (LookCorp.submenuTimeout) { 
                clearTimeout(LookCorp.submenuTimeout);
                LookCorp.submenuTimeout = null;
            }
            
            // Set a timeout to expand this item
            var target = this;
            LookCorp.submenuTimeout = setTimeout(function() { 
                $('ul', target).slideDown('normal', function() {
                    // IE7 doesn't realise it needs to redraw the li below the one that just expanded
                    // Hiding then showing makes it redraw
                    if ($.browser.msie) $('#navMenu li.autoOpen').hide().show();
                });
            }, 300);
        });
    $('#navMenu li.autoOpen').mouseout(
        // If there's any existing timeout, clear it
        function() {
            if (LookCorp.submenuTimeout) { 
                clearTimeout(LookCorp.submenuTimeout);
                LookCorp.submenuTimeout = null;
            }
        });
    $('#navMenu').mouseout(
        function(ev) {
            // Figure out if mouse is still in #navMenu
            var navMenu = $('#navMenu');
            var offset = navMenu.offset();
            var d = { left: offset.left, top: offset.top, right: offset.left + navMenu.width(), bottom: offset.top + navMenu.height() };
            if (ev.pageX > d.left && ev.pageX < d.right && ev.pageY > d.top && ev.pageY < d.bottom) {
                // mouse is still inside #navMenu
            } else {
                $('#navMenu li.autoOpen ul').slideUp('fast');
            }
        });
        
    // Keyboard version - only slides down, not up (its a bit hard to tell when the ul blur event happens)
    $('#navMenu li.autoOpen').focus(
        function() {
            $('ul', this).slideDown('normal', function() {
                if ($.browser.msie) $('#navMenu li.autoOpen').hide().show();
            });
        });
});

/* Iframe handler */
// From http://sonspring.com/journal/jquery-iframe-sizing
$(document).ready(function()
{
    try {
        if (document.location.host.indexOf('shoparound') > 0) {
            document.domain = "shoparound.com.au"; 
        }
    } catch (e) {
        // Do nothing - we must be on a different domain
    }
    
    // Set specific variable to represent all iframe tags.
    var iFrames = $('iframe.partnerRd').get();

    $('iframe.partnerRd').ready(function()
    {
        if (LookCorp.ModalUpdateProgress) LookCorp.ModalUpdateProgress.showPopup();
    });

    // Make sure pdf links in iframes pop a new window
    $('iframe.partnerRd').load(function()
    {
        // Hide the loading div
        // $('.loadingIframe').hide();
        if (LookCorp.ModalUpdateProgress) LookCorp.ModalUpdateProgress.cancel();

        var contentDoc = this.contentWindow.document || this.parentNode.document.frames["partnerRd"].document;
        try {
            $('a[href$=.pdf]', contentDoc).click(function(event) {
                window.open(this.href);
                event.preventDefault();
            });
            
            $('a[href^=http://www.artog.com.au/]', contentDoc).click(function(event) {
                this.href = this.href.replace("RATE_DETECTIVE", "SHOP_AROUND");
                window.open(this.href);
                event.preventDefault();
            });
        } catch (e) { }
        
        // Scroll to top when we navigate a link
        var topElement = $('#highlevelTabsWrapper', contentDoc)[0];
        if (topElement) topElement.scrollIntoView();
        
        // Hide ads - this is a temp fix
        // $('img[src^=http://www.s2d6.com/], img[src^=http://members.commissionmonster.com/]', contentDoc).hide();
        
        // Give us a notification of conversions
        $('form[action$=mortgage-enquiry.htm]', contentDoc).submit(function(ev) {
            // TODO remove these 2 lines in production
            // alert('Caught submit');
            // ev.preventDefault();
            
            var baseDir = SizeSwitcher.baseDir;
            if (!baseDir) baseDir = '/controls/';
            var url = baseDir + "PartnerAction.ashx?";
            url += "p=rd";
            url += "&a=form";
            url += "&name=" + encodeURIComponent($('#edit-submitted-mortgage-enquiry-form-name').val());
            
            var img = new Image();
            img.src = url;
        });
        
        $('a[href^=http://www.s2d6.com/], a[href^=http://members.commissionmonster.com/], a[href^=http://www.artog.com.au/]', contentDoc).click(function(ev) {
            // Log external href click
            var baseDir = SizeSwitcher.baseDir;
            if (!baseDir) baseDir = '/controls/';
            var url = baseDir + "PartnerAction.ashx?";
            url += "p=rd";
            url += "&a=link";
            url += "&link=" + encodeURIComponent(this.href);
            
            var img = new Image();
            img.src = url;
        });
    });

    // Resize heights.
    function iResize()
    {
        // Iterate through all partner iframes in the page.
        for (var i = 0, j = iFrames.length; i < j; i++)
        {
            // Set inline style to equal the body height of the iframed content.
            iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';
        }
    }

    // Check if browser is Safari or Opera.
    if ($.browser.safari || $.browser.opera)
    {
        // Start timer when loaded.
        $('iframe.partnerRd').load(function()
        {
            setTimeout(iResize, 0);
        }
        );

        // Safari and Opera need a kick-start.
        for (var i = 0, j = iFrames.length; i < j; i++)
        {
            var iSource = iFrames[i].src;
            iFrames[i].src = '';
            iFrames[i].src = iSource;
        }
    }
    else
    {
        // For other good browsers.
        $('iframe.partnerRd').load(function()
        {
            // Set inline style to equal the body height of the iframed content.
            this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
        }
        );
    }
}
);

/* Font size switcher class */
var SizeSwitcher = {
    baseDir: '',
    cookieName: '',
    setText : function(elem, size) { 
        document.cookie = this.cookieName + '=' + escape(size) + ';expires=' + new Date('December 31, 2020 23:59:59').toGMTString() + ';path=/;';
        
        var linkElement = $id("textSize");
        if (size == 0) {
            // Remove element
            this.addStylesheetRef("");
        } else if (size == -1) {
            this.addStylesheetRef(this.baseDir + "text-small.css");
        } else if (size == 1) {
            this.addStylesheetRef(this.baseDir + "text-large.css");
        } else if (size == 2) {
            this.addStylesheetRef(this.baseDir + "text-xlarge.css");
        }
        
        // Remove 'selected' class from other links
        var links = elem.parentNode.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            if (link.className == "selected") link.className = "";
        }
        elem.className = "selected";
        
        
    },

    addStylesheetRef : function(href) {
        if (href == "") {
            var linkElement = $id("textSize");
            if (linkElement) {
                linkElement.setAttribute("href", "");
                linkElement.parentNode.removeChild(linkElement);
                this.fireSwitchEvent();
            }
            return;
        }

        // preload the css using an iframe. Its onload event fires when it has finished loading.
        $(LookCorp.substitute('<iframe src="{0}" style="display: none;" onload="SizeSwitcher.onIframeLoad(this);"></iframe>', href.replace(".css", ".aspx"))).appendTo('body');
    },
    
    onIframeLoad : function(iframe) {
        // stylesheet has loaded, add a link to it in the head
        var linkElement = $id("textSize");
        if (linkElement == null) {
            linkElement = document.createElement("link");
            linkElement.setAttribute("id", "textSize");
            linkElement.setAttribute("rel", "stylesheet");
            linkElement.setAttribute("type", "text/css");
            document.getElementsByTagName("head")[0].appendChild(linkElement);
        }
        var doc = (iframe.contentDocument || iframe.contentWindow.document); // IE gives it a different name
        linkElement.setAttribute("href", doc.getElementsByTagName("link")[0].getAttribute("href"));
        
        this.fireSwitchEvent();
         
        // if we remove the iframe during its onload event, firefox won't remove 'loading...' from the
        // window title. So we delay it a little
        setTimeout(function() { iframe.parentNode.removeChild(iframe); }, 20);
    },
    
    getCurrentSize : function() {
        size = this.readCookie(this.cookieName);
        if (size) {
            return parseInt(size, 10);
        } else {
            return 0;
        }
    },
    
    // Get the scaling factor for the current size
    getCurrentRatio : function() {
        var textSize = this.getCurrentSize();
        
        if (textSize == -1)
            return 0.91; // ratio of 12px to 11px (small)
        else if (textSize == 1)
            return 1.08; // ratio of 12px to 13px (large)
        else if (textSize == 2)
            return 1.25; // ratio of 12px to 15px (xlarge)
        else
            return 1.00;
    },
    
    readCookie : function(name) { // from http://www.quirksmode.org/js/cookies.html
	    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;
    },
    
    /* Allow other javascript to be notified of size changes. eg. Popup Quote has to redraw itself */
    observerList : new Array(),
    addSwitchListener : function(obj) {
        for (var i = 0; i < this.observerList.length; i++) {
            if (this.observerList[i] == obj) return; // prevent duplicates
        }
        this.observerList.push(obj);
    },
    removeSwitchListener : function(obj) {
        for (var i = 0; i < this.observerList.length; i++) {
            if (this.observerList[i] == obj) observerList[i] = null;
        }
    },
    fireSwitchEvent : function() {
        for (var i = 0; i < this.observerList.length; i++) {
            if (this.observerList[i] != null && typeof(this.observerList[i].onSizeChange) == 'function') this.observerList[i].onSizeChange(this.observerList[i]);
        }
    }
};

/**********************************************************************
 * ResizableImage class
 **********************************************************************/
LookCorp.ResizableImage = function(id) {
    this.id = id;
    
    SizeSwitcher.addSwitchListener(this);
};

LookCorp.ResizableImage.suffixMap = {
    '-1' : 'small',
    '0'  : 'medium',
    '1'  : 'large',
    '2'  : 'xlarge'
};

LookCorp.ResizableImage.prototype.onSizeChange = function(img) {
    var suffix = LookCorp.ResizableImage.suffixMap[SizeSwitcher.getCurrentSize() + ""]; // empty string just converts number to string
    var image = $id(this.id);
    var src = image.getAttribute("src");
    // regex gets the bit in brackets in the following string: imagename(.suffix).jpg
    // the brackets starting with (?= is required for a match, but not included in the returned match
    //TODO have this appear in the task list
    src = src.replace(/\.\w{5,6}(?=\.\w{3,4})/, "." + suffix);
    image.setAttribute("src", src);
    
    // We may need to change the CSS class of a parent <a> tag
    // if this is a special rollover image
    var parent = image.parentNode;
    if ((parent.nodeType == 1) && (parent.tagName.toLowerCase() == "a"))
    {
        if (parent.className.search(/^rollover[^_]+_[^_]{5,6}/) >= 0) {
            parent.className = parent.className.replace(/_\w*$/, "_" + suffix);
        }
    }
};

/**********************************************************************
 * ResizableFlash class
 *
 * This class is only needed when embedding dynamically. Otherwise
 * width and height can be given in ems.
 **********************************************************************/
LookCorp.ResizableFlash = function(id, normalWidth, normalHeight) {
    this.id = id;
    this.normalWidth = normalWidth;
    this.normalHeight = normalHeight;
    
    SizeSwitcher.addSwitchListener(this);
};

LookCorp.ResizableFlash.prototype.onSizeChange = function(obj) {
    var outerObject = $id(this.id);
    var innerObjects = outerObject.getElementsByTagName("object");
    var innerObject = innerObjects.length > 0 ? innerObjects[0] : null;
    
    var ratio = SizeSwitcher.getCurrentRatio();
    var width = parseInt(this.normalWidth * ratio);
    var height = parseInt(this.normalHeight * ratio);
    
    outerObject.setAttribute("width", width);
    outerObject.setAttribute("height", height);
    
    if (innerObject) {
        innerObject.setAttribute("width", width);
        innerObject.setAttribute("height", height);
    }
};

/**********************************************************************
 * Popup quote class
 **********************************************************************/
// Constuctor - gets called like this: 'var p = new LookCorp.PopupQuote('abc', 'The text', { options });'
LookCorp.PopupQuote = function(id, text, options) {
    // TODO handle if something with the same id exists
    this.id = id;
    this.text = text;
    var options = options || {};
    $.extend(this, LookCorp.PopupQuote.defaults, options); // apply options
    
    // Start listening to size switch events
    if (SizeSwitcher) {
        SizeSwitcher.addSwitchListener(this);
    }
};

// Setting defaults
LookCorp.PopupQuote.defaults = { 
    width: 200, // popup width
    height: 200, // popup height
    top: 0, // if absolutely positioned, y co-ordinate
    left: 0, // if absolutely positioned, x co-ordinate
    targetElement: null, // dom element to point at
    pointerDirection: 'l', // direction to point: l, r, u, d
    pointerPathPrefix : '', // path to the pointer image directory
    pointerPadding: 30, // spacing from edge of popup to pointer
    pointerWidth: 23, // width of pointer image
    pointerHeight: 11, // height of pointer image
    shadowPath : 'shadow.png', // shadow image name
    shadowSize: 4, // no. of pixels to offset shadow image
    showClose: true, // option to show close image
    closePath: 'close.png', // close image name
    cssClass: null // extra css class
    };
    
// Gets the javascript PopupQuote object for an id
LookCorp.PopupQuote.getInstance = function(id) {
    var element = $id(id);
    if (element && element.popupQuoteObj) return element.popupQuoteObj;
    else return null; 
};

// Event handler for when a callback occurs
LookCorp.PopupQuote.onCallback = function() {
    setTimeout(LookCorp.PopupQuote.onWindowResize, 20); // delay to make sure browser has drawn changes
};

// Event handler for when the window resizes
LookCorp.PopupQuote.onWindowResize = function() {
    var vi = LookCorp.PopupQuote.visibleInstances;
    for (var i = 0; i < vi.length; i++) {
        if (vi[i]) vi[i].show(true);
    }
};

// array to keep track of visible popup quotes (for redraw events) 
LookCorp.PopupQuote.visibleInstances = [];

//$(window).resize(LookCorp.PopupQuote.onWindowResize); // add a handler to window.onResize

// popup quote properties
LookCorp.PopupQuote.prototype.pointerImages = { 'l': 'Left.png', 'r': 'Right.png', 'u': 'Up.png', 'd': 'Down.png' }; // path to various pointer images
LookCorp.PopupQuote.prototype.id = ''; // id of popup quote
LookCorp.PopupQuote.prototype.text = ''; // text(html) to display in quote
LookCorp.PopupQuote.prototype.visible = false; // indicates if the popup quote is visible (for read only)

// popup quote functions

// renders the popup quote
LookCorp.PopupQuote.prototype.show = function(dontRecreate) { // dontRecreate should only be used internally (used by onWindowResize)
    dontRecreate = !!dontRecreate; // becomes false if not supplied, or boolean value if supplied
    
    if (!dontRecreate) {
        // Remove previous rendering
        $(LookCorp.substitute('#{0}, #{1}Shadow, #{2}Pointer', this.id, this.id, this.id)).remove();
        
        // Render quote & rounded corner markup
        $('<div id="' + this.id + '" class="popupQuote">'
            + '<div class="header"><div class="nw"></div><div class="n"></div><div class="ne"></div></div>'
            + '<div class="body">' + this.text + '</div>'
            + '<div class="footer"><div class="sw"></div><div class="s"></div><div class="se"></div></div>' 
            + '</div>').appendTo('body');
    }
    var popupQuote = $('#' + this.id);
    
    if (this.cssClass) {
        popupQuote.addClass(this.cssClass);
    }
       
    var cLeft = 0, cTop = 0, cWidth = this.width, cHeight = this.height; // computed left/right width/height
    if (SizeSwitcher) {
        // adjust pixel dimensions for user's font size preference
        var currentRatio = SizeSwitcher.getCurrentRatio();
        cWidth = parseInt(cWidth * currentRatio, 10);
        cHeight = parseInt(cHeight * currentRatio, 10);
    }
    
    if (!this.targetElement) {
        // no element, absolutely position
        cTop = this.top;
        cLeft = this.left;
    } else {
        // point at a dom element
        var targetElementPos = LookCorp.getPosition(this.targetElement); // TODO use jquery equivalent
        var targetHeight = $(this.targetElement).height();
        var targetWidth = $(this.targetElement).width();
        cTop = targetElementPos['y'];
        cLeft = targetElementPos['x'];
        
        // figure out where we need to be to point the right direction
        var halfPointerWidth = parseInt(this.pointerWidth / 2);
        switch (this.pointerDirection) {
            case 'l':
                cTop += (targetHeight / 2);
                cTop -= this.pointerPadding + halfPointerWidth;
                cLeft += this.pointerHeight + targetWidth;
                break;
            case 'r':
                cTop += (targetHeight / 2);
                cTop -= this.pointerPadding + halfPointerWidth;
                cLeft -= this.pointerHeight + cWidth;
                break;
            case 'u':
                cTop += this.pointerHeight + targetHeight;
                cLeft -= this.pointerPadding + halfPointerWidth;
                break;
            case 'd':    
                cTop += this.pointerHeight + cHeight;
                cLeft -= this.pointerPadding + halfPointerWidth;
                break;
            default:
                // do nothing
        }
    }
    
    // sanitise top/left so we don't try and draw off the screen
    if (cTop < 0) cTop = 0;
    if (cLeft < 0) cLeft = 0;
    
    // apply top/left/width/height
    popupQuote.css('top', cTop + 'px');
    popupQuote.css('left', cLeft + 'px');
    popupQuote.css('width', cWidth + 'px');
    popupQuote.css('height', cHeight + 'px');
    
    // store the javascript PopupQuote object on the dom element (for use by getInstance)
    popupQuote.get(0).popupQuoteObj = this;
    
    // set width/height of content area
    $('.body', popupQuote).css('height', (cHeight - 14) + 'px'); // 14 = 2 * 4px rounded corners + 2 * 3px padding top/bottom
    $('.n, .s', popupQuote).css('width', (cWidth - 8) + 'px'); // 8 = 2 * 4px rounded corners
    
    // close image
    if (this.showClose && !dontRecreate) {
        var closeImg = $('<img class="close" src="' + this.closePath + '" />');
        closeImg.get(0).popupQuoteObj = this;
        closeImg.click(function() { this.popupQuoteObj.hide(); }); // when clicked, 'this' refers to the image
        closeImg.appendTo(popupQuote);
    }
    
    // pointer image
    var pointerSrc = this.pointerPathPrefix + this.pointerImages[this.pointerDirection];
    if (!dontRecreate) {
        $('<image id="' + this.id + 'Pointer" class="popupQuotePointer" src="' + pointerSrc + '" />').appendTo('body');
    }
    var pointerImage = $('#' + this.id + 'Pointer');
    pointerImage.attr('src', pointerSrc); // set this again in case it has changed
    
    // figure out where the pointer image needs to be to point the right way
    switch (this.pointerDirection) {
        case 'l':
            pointerImage.css('left', (cLeft - this.pointerHeight + 1) + 'px');
            pointerImage.css('top', (cTop + this.pointerPadding) + 'px');
            break;
        case 'r':
            pointerImage.css('left', (cLeft + cWidth - 1) + 'px');
            pointerImage.css('top', (cTop + this.pointerPadding) + 'px');
            break;
        case 'u':
            pointerImage.css('bottom', (cTop + 1) + 'px');
            pointerImage.css('left', (cLeft + this.pointerPadding) + 'px');
            break;
        case 'd':
            pointerImage.css('top', (cTop + cHeight - 1) + 'px');
            pointerImage.css('left', (cLeft + this.pointerPadding) + 'px');
            break;
        default:
            // hide pointer
            pointerImage.hide();
    }
    
    // Shadow image
    if (!dontRecreate && !($.browser.msie && $.browser.version <= 6 )) { // dont show shadow for IE <= 6
        $('<image id="' + this.id + 'Shadow" class="popupQuoteShadow" src="' + this.shadowPath + '" />').appendTo('body');
    }
    var shadowImage = $('#' + this.id + 'Shadow');
    shadowImage.attr('src', this.shadowPath);
    shadowImage.css('width', cWidth + 'px');
    shadowImage.css('height', cHeight + 'px');
    shadowImage.css('top', (cTop + this.shadowSize) + 'px');
    shadowImage.css('left', (cLeft + this.shadowSize) + 'px');
    
    this.visible = true;
    
    // add to visible instances array
    var found = false, vi = LookCorp.PopupQuote.visibleInstances;
    for (var i = 0; i < vi.length; i++) {
        if (vi[i] == this) {
            found = true;
            break;
        }
    }
    if (!found) { vi.push(this); }
};

// hides the popup quote
LookCorp.PopupQuote.prototype.hide = function() {
    $(LookCorp.substitute('#{0}, #{1}Shadow, #{2}Pointer', this.id, this.id, this.id)).hide();
    this.visible = false;
    
    // remove from visible instances array
    var vi = LookCorp.PopupQuote.visibleInstances;
    for (var i = 0; i < vi.length; i++) {
        if (vi[i] == this) vi[i] = null;
    }
};

// event handler for a text size change
LookCorp.PopupQuote.prototype.onSizeChange = function(obj) {
    if (obj.visible) {
        obj.show();
    }
};

// points the popup quote at either an element, or an x/y co-ordinate
LookCorp.PopupQuote.prototype.positionAt = function(x, y) {
    // Change position to point at element
    if (typeof(x) == 'number') {
        this.targetElement = null;
        this.top = x;
        this.left = y;
    } else if (typeof(x) == 'object') {
        this.targetElement = x;
        this.top = -1;
        this.left = -1;
    }
};

LookCorp.PopupQuote.prototype.replaceText = function(text) {
    this.text = text;
    $(LookCorp.substitute('#{0} .body', this.id)).empty().append(text);
};

/*****************************************
 * Content Preloader
 *****************************************/
LookCorp.PreLoader = function() {
    this.items = [];
    this.index = -1;
};

LookCorp.PreLoader.prototype.loadNext = function(t) {
    if (!t) t = this;
    this.index++;
    if (t.index < t.items.length) {
        try {
            $.ajax({
                type : "GET",
                url : t.items[t.index], 
                success : function() { t.loadNext(t) }
                });
        } catch (e) {
            // Could be a same origin error, try the image method
            var image = new Image();
            image.src = t.items[t.index]; // 'this' is the options passed to the $.ajax call
            t.loadNext(t);
        }
    }
};

LookCorp.PreLoader.prototype.go = function() {
    this.loadNext();
};

