$(document).ready(function () {

    // Declare variables
    var tabWidgetBanking = new Tab('#widgetBanking');
    var pageName = $('meta[name=pageName]').attr('content');

    // Collage - Hack:
    // Clean up Collages messy code
    // ---------------------------------------------
    $('div#thessm').remove();

    var printCSS = $('link[href$=print.css]');

    if (printCSS.next().is('script')) {
        printCSS.next().remove();
    }

    if (printCSS.next().is('script')) {
        printCSS.next().remove();
    }
    // ---------------------------------------------

    // Set body padding size to correct height of the footer (to accommodate for custom content, plus a bit of spacing to prevent 'page shrinking')
    $('#container #body').css('padding-bottom', parseInt($('#container #footer').height(), 10) + 30 + 'px');


    // Resize the #container height so the footer always sits on bottom of page
    // ---------------------------------------------
    $(window).bind('resize', function () {

        if ($('#container').height() < $(window).height()) {
            $('#container').css('height', $(window).height());
        }

    });
    $(window).resize();


    // Navigation Main - Set Active Class to current page
    // ---------------------------------------------
    if (0 == $('#navigationMain li.active').length) {
        var sectionName = $('meta[name=sectionName]').attr('content');

        var currentMainNav = $("#navigationMain li a:contains('" + sectionName + "')");

        currentMainNav = currentMainNav.parent();

        currentMainNav.attr('class', 'active');
    }

    // Navigation Main - Set Active Class to homepage (if current page is homepage)
    // ---------------------------------------------
    if ('PNCS' == pageName) {
        $("#navigationMain li:first").addClass('active');
    }

    // Navigation Left - Set Active Class to current page and parent
    // ---------------------------------------------
    var currentLeftNav = $("#navigationLeft li[class!='active'] a:contains('" + pageName + "')");

    if (pageName == currentLeftNav.html()) {
        currentLeftNav = currentLeftNav.parent();

        currentLeftNav.attr('class', 'active');

        if (currentLeftNav.parent().parent().is('li')) {
            currentLeftNav.parent().parent().attr('class', 'active');
        }
    }

    // Breadcrumb - If no breadcrumb exists add in the page name
    // ---------------------------------------------
    if (1 == $('#breadcrumb li').length) {
        $('#breadcrumb').append('<li>' + pageName + '</li>');
    }

    // Webchat - Handle turning webchat on and off
    // ---------------------------------------------
    var webChat = new WebChat();

    // Text Resizing
    // ---------------------------------------------
    if ($.cookie('fontSize')) {
        resizeText($.cookie('fontSize'));
    }

    // Text sizing
    $('#textResizer img#textSmall').click(function () { resizeText('0.70em'); });
    $('#textResizer img#textMedium').click(function () { resizeText('0.9em'); });
    $('#textResizer img#textLarge').click(function () { resizeText('1.1em'); });
    // ---------------------------------------------

    // Search
    // ---------------------------------------------
    $('#query').bind('click', function () {

        if ('Search' == $('#query').val()) {
            $('#query').val('');
        }

    });

    $('#query').bind('blur', function () {

        if ('' == $('#query').val()) {
            $('#query').val('Search');
        }

    });

    // Quick Menu - Bind - Select Events
    // ---------------------------------------------
    $('#quickMenu select').bind('change', function () {

        if ($(this).attr('value').length > 0) {
            switch ($(this).attr('id')) {
                case 'iLooking':

                    window.location = $(this).attr('value');
                    break;

                case 'iApply':
                case 'iEnquire':

                    switch ($(this).attr('value')) {
                        case 'https://secure.zurich.com.au/ezicover/pncs/home.htm':
                        case 'http://www.gmhba.com.au/webjoin/quote.asp?ID=136':

                            window.open($(this).attr('value'), $(this).attr('id'), 'width=850,height=750,address=0,toolbar=0,status=0,scrollbars=1');
                            //							window.location = $(this).attr('value');
                            //							break;

                        case 'https://direct.membercare.com.au/b2c/quotemaster_b2c/newQuote.action?orgId=251&riskType=HOME':
                        case 'https://direct.membercare.com.au/b2c/quotemaster_b2c/newQuote.action?orgId=251&riskType=MOTOR':

                            window.open($(this).attr('value'), $(this).attr('id'), 'width=770,height=750,address=0,toolbar=0,status=0,scrollbars=1');
                            break;

                        default:
                            window.open($(this).attr('value'), $(this).attr('id'), 'width=720,height=550,address=0,toolbar=0,status=0,scrollbars=1');
                    }
            }
        }

    });

    // Temporary way to ensure certain URLS open in a new window
    // ---------------------------------------------
    $('a').bind('click', function () {

        switch ($(this).attr('href')) {
            case 'http://116.212.196.69/forms/GeneralEnquiryForm.aspx':
            case 'http://116.212.196.72/forms/GeneralEnquiryForm.aspx?orgcode=1/forms/GeneralEnquiryForm.aspx':
            case 'https://www.pncs.com.au/forms/GeneralEnquiryForm.aspx?orgcode=1/forms/GeneralEnquiryForm.aspx':
            case 'https://www.pncs.com.au/forms/GeneralEnquiryForm.aspx':
            case 'https://www.pncs.com.au/webchat/pncs/index.jsp':
                {
                    window.open($(this).attr('href'), 'popup', 'width=700,height=550,address=0,toolbar=0,status=0,scrollbars=1');
                    return false;
                    break;
                }
            case 'https://www.pncs.com.au/talk/chat.aspx?QueueName=PNCS':
                {
                    window.open($(this).attr('href'), 'popup', 'width=750,height=630,address=0,toolbar=0,status=0,scrollbars=1');
                    return false;
                    break;
                }
            case 'http://broker.pncs.com.au':
            case 'http://broker.pncs.com.au/':
            case 'https://broker.pncs.com.au':
            case 'https://broker.pncs.com.au/':
                {
                    window.open($(this).attr('href'), 'popup', 'width=1200,height=800,address=1,toolbar=1,location=1,status=1,scrollbars=1,menubar=1,resizable=1');
                    return false;
                    break;
                }
            case 'https://direct.membercare.com.au/b2c/quotemaster_b2c/newQuote.action?orgId=251&riskType=MOTOR':
            case 'https://direct.membercare.com.au/b2c/quotemaster_b2c/newQuote.action?orgId=251&riskType=HOME':
                {
                    window.open($(this).attr('href'), 'popup', 'width=770,height=750,address=0,toolbar=0,status=0,scrollbars=1');
                    return false;
                    break;
                }
            case 'https://netlink.pncs.com.au/806015v47/pncs47.asp':
                {
                    window.open($(this).attr('href'), 'popup', 'width=990,height=700,address=0,toolbar=0,status=0,scrollbars=1,resizable=1');
                    return false;
                    break;
                }
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Perth HQ':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Belmont':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Booragoon':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Bunbury':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Cannington':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Fremantle':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Innaloo':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Joondalup':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Maddington':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Mandurah':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Midland':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Morley':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Ocean Keys':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Perth':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Rockingham':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Success':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Warwick':
            case 'http://www.pncs.com.au/maps/Branch.htm?bid=Whitfords':
                {
                    window.open($(this).attr('href'), 'popup', 'width=710,height=770');
                    return false;
                    break;
                }
        }
    });

});


/**
 * -------------------------------------
 * Tab
 * Handles tab functionality
 * -------------------------------------
 */
var Tab = function(id)
{
	// Declare variables
	var _id = id;


	/**
	 * init()
	 *
	 * Initialize tabs
	 */
	this.init = function()
	{
		var self = this;

		// Bind event - click - Tab - map
		$(_id + ' ul li').bind('click', function(){

			self.setActive(this);

			return false;

		});
	},

	/**
	 * setActive()
	 *
	 * Set Active Tab
	 * @param object obj
	 */
	this.setActive = function(obj)
	{
		// Declare variables
		obj				= $(obj);
		var className	= obj.find('a').attr('class');

		// If current class is active the return
		if( 'active' == obj.attr('class') )
		{
			return;
		}
			
		// Change Active Tab
		$(_id + ' ul li').each(function(){

			$(this).attr('class', '');

		});

		// Set selected tab to active
		$(_id + ' ul li a.' + className).parent().attr('class', 'active');

		// Fade out tab content then fade in tab content that has been selected
		$(_id + ' div').hide();

		$(_id + ' div.' + className).show();
	}

	// Call Init()
	this.init();
}


/**
 * -------------------------------------
 * WebChat
 * Handles webchat on / off functionality
 * -------------------------------------
 */
var WebChat = function () {
    // Declare variables
    var _holidays = new Array(
						'27/12/2010',
						'28/12/2010',
						'03/01/2011',
                        '26/01/2011',
                        '07/03/2011',
                        '22/04/2011',
                        '25/04/2011',
                        '26/04/2011',
                        '06/06/2011',
                        '03/10/2011',
			'28/10/2011',
                        '26/12/2011',
                        '27/12/2011',
			'02/01/2012',
			'26/01/2012',
			'05/03/2012',
			'06/04/2012',
			'09/04/2012',
			'25/04/2012',
			'04/06/2012',
			'01/10/2012',
			'25/12/2012',
			'26/12/2012',
                        '01/01/2013');

    /**
    * init()
    *
    * Initialize tabs
    */
    this.init = function () {
        // Declare variables
        var self = this;
        var chatActive = this.isTodayHoliday(); // change this to "0" to turn webchat image link OFF
        //var chatActive = 0;

        if ((location.href.search("metaweb") != -1) || (chatActive == 0)) {
            this.setChatOffline();
        }
        else {
            // Create new Date object with current date/time
            var now = new Date();
            var hours = now.getUTCHours(); // Get the hours in UTC from the current time
            var day = now.getDay();

            // Daylight savings quick fix - uncomment below line to add 1 hour to the time
            //hours++;
            if (hours > 23) {
                hours = 0;
            }

            // Contact Center is open from 8am to 6pm WA time (GMT+8), which is UTC 0 to 10 hours
            //if( ( hours >= 0 ) && ( hours < 10 ) && ( day >= 1 ) && ( day < 6 ) )
            if (hours < 0 || hours >= 10 || 0 == day || 6 == day) {
                this.setChatOffline();
            }
        }
    },

    /**
    * isTodayHoliday()
    *
    * Determine if today is a holiday
    * Note: This list needs to be updated at the beginning of each year.
    * @return boolean
    */
	this.isTodayHoliday = function () {
	    // Declare variables
	    var returnValue = true;
	    var today = this.getDate();

	    for (i = 0; i < _holidays.length; i++) {
	        if (today == _holidays[i]) {
	            returnValue = false;
	        }
	    }

	    return returnValue;
	},

    /**
    * getDate()
    *
    * Gets the current date
    * @return string dd/mm/yyyy
    */
	this.getDate = function () {
	    // Declare variables
	    var currentTime = new Date();
	    var month = currentTime.getMonth() + 1;
	    var day = currentTime.getDate();
	    var year = currentTime.getFullYear();

	    if (day.toString().length < 2) {
	        day = "0" + day;
	    }

	    if (month.toString().length < 2) {
	        month = "0" + month;
	    }

	    return day + "/" + month + "/" + year;
	},

    /**
    * setChatOffline()
    *
    * Set the chat to offline
    */
	this.setChatOffline = function () {
	    $('div.moduleWebChat').load('/Include/SidebarRight/moduleWebChatClosed.html', function () { });
	}

    // Call Init()
    this.init();
}


/*
 * Font resizing function
 *
 * @param float size
 * @return void
 */
function resizeText(size)
{
	// Update fontsize
    $('body').css('font-size', size);

	// Set cookie
    $.cookie('fontSize', size, { expires: 7 });
}



/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights"
 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
 *
 * Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights or widths of the top-level children of a provided element 
 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
 		by default if pxToEm() method is available.
 * Dependencies: jQuery library
 * Usage Example: $(element).equalHeights();
 * Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});

		// for ie6, set height since min-height isn't supported
		if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
	return this;
};

function SearchText()
{
    document.getElementById('q').value = "";
}
