var counton = {

    //all 
    //debug: ["menu","ajax","page","content"],
    debug: ["ajax", "page", "content", "menu"],

    /* page types:
    get populated from the menu, possibly in future from service...
    */

    pageTypeFunctions: {},


    //use ajax removes or deletes hrefs on certain elements and their <a> parents specified in ajaxElements
    useAjax: false,
    ajaxElements: 'div.menuItem',

    pageType: { '/privacy-policy.aspx': 'content' },
    menuOptions: {},
    menuOptionsB: {},
    centerPage:false,
    resizePage:false,
    
    //does the page need to be filled using the fillElement element (jquery selector) and offset off the fillExisting 
    FillPage:false,
    fillElement:'#mainContent',
    fillExisting:176,
    //minimum size of fillelement
    fillMin:550,
    fillPageMin:727,
    Title:'SECUREcorp',
        
    
/************************************************ end settings ****************************************************/

    scrollableApi: {},
    getRelativeUrl: function ()
    {
        return $.url.attr('path');
    },
    
    
    changeFont: function(buttonSelector,selector,ratio) 
    {
		$(buttonSelector).click(function(){
			var ourText = $(selector);
			var currFontSize = ourText.css('fontSize');
			var finalNum = parseFloat(currFontSize, 10);
			var stringEnding = currFontSize.slice(-2);
			if(this.id == 'big') {
				finalNum *=ratio;
			}
			else if (this.id == 'small'){
				finalNum /=ratio;
			}
			ourText.css('fontSize', finalNum + stringEnding);
		});
    },

    pageTypeCommonFunction: function(){},
    pageTypeCommonFunctionLoad: function()
    {
	
        for (var func in counton.pageTypeFunctions)
        {
            if (func.substr(0,1) != 'i')
            {
                counton.pageTypeFunctions['i'+func] = counton.pageTypeFunctions[func];
                counton.pageTypeFunctions[func] = Function("href","html",
                    "counton.pageTypeCommonFunction();"+
                    "counton.pageTypeFunctions['"+'i'+func+"'](href,html);"
                );
            }
        }
    },

    TextBox:{
        prepare:function(klass) {
            $(klass).attr('firstClick','0');
            $(klass).click(function() {
                if ($(this).attr('firstClick') == '0')
                {
                    $(this).attr('value','').attr('firstClick','1');
                }
            });
        }
    },
    getAbsolutePosition: function(element, stopAt) {
        var r = { x: element.offsetLeft, y: element.offsetTop };
        if (element.offsetParent && element.offsetParent.id != stopAt) {
            counton.log("absolute pos: " + element.offsetParent.id + " stop:" + stopAt, "menu");
            var tmp = counton.getAbsolutePosition(element.offsetParent);
            r.x += tmp.x;
            r.y += tmp.y;
        }
        return r;
    },
    fillPage: function(element,exitsting) {
        var height = $(window).height();
        var extraSpace = height - exitsting;
        if (extraSpace >0 && extraSpace > counton.fillMin)
        {
            $(element).height(extraSpace);
            counton.customization.fillPageCustom();
        }
        else
        {
            counton.customization.fillPageCustomRem(extraSpace-counton.fillMin);
        }
    },
    posMiddle: function() {
        var height = $(window).height();
        var extraSpace = height - 620;
        if (extraSpace > 0) {
            $("div#container").css({ 'position': 'relative', 'top': Math.round(extraSpace / 2) });
        }
    },
    posContent: function() {
        var left = $("div#container").offset().left;
        var top = $("div#container").offset().top;
        $("div#mainContent").css({ "left": Math.round(left + 330) + "px", "top": top + "px" });
    },
    onResize: function() {
        //counton.posMiddle();
        //posContent();
    },

    /*******************************************************************************************/
    forceAjaxGoto: function(href) {

        this.loading(true);
        $.ajax({
            url: href,
            cache: false,
            dataType: "html",
            success: function(html) {
                counton.animateContent(href, html);
                counton.log("forceAjaxGoto{ href:" + href + "  htmlLength: " + html.length + " }", "ajax");
            }
        });
    },
    getAjaxHref: function(selected) {
        selected = selected.toString();
        var start = selected.indexOf("ajaxGoto(") + 10;
        var sngle = selected.indexOf('")');
        var dble = selected.indexOf("')");
        var end;
        if (sngle > -1) {
            end = sngle;
        }
        else {
            end = dble;
        }
        var length = end - start;
        var curHref = selected.substr(start, length);
        return curHref;
    },
    ajaxGoto: function(href) {
        //check if href is current

        var selected = "";
        if ($("div.menuItem[selected=true]").length > 0) {
            selected = $("div.menuItem[selected=true]").attr('onclick').toString();
        }
        var curHref = this.getAjaxHref(selected);
        // if (curHref != href) {
        $(document).trigger('counton.beforeAnimateContent');
        //this.updateLogin();
        this.beforeAnimate(href);
        this.setTitle(this.menuOptionsB[href]);
        this.unAnimateContent(curHref, href);
        counton.log("ajaxGoto{ href:" + href + " }", "ajax");
        this.forceAjaxGoto(href);
        //}
    },


    /************************* animate section *******************************/
    beforeAnimate: function(href) {
        //show secondary menu
        //alert('div.menuItem[parent='+this.menuOptionsB[href]+']');
        //this.loadSubPage($('div.subMenuItem[parent='+this.menuOptionsB[href]+']:first').attr('id'));
    },
    animateContent: function(href, html) {
        counton.log("animateContent { href:" + href + "  counton.pageType[href]: " + counton.pageType[href] + " }", "content");

        //call animate each page type
        if (typeof (counton.pageType[href]) != "undefined" && typeof (counton.pageTypeFunctions[counton.pageType[href]]) != "undefined") {
            counton.pageTypeFunctions[counton.pageType[href]](href, html);
        }
	else
	{
	  //call the common function
	  counton.pageTypeCommonFunction();
	}


        //custom for non-pagetype pages
        if (href == '/contact.aspx') {
        }
    },


    pageAnimated: false,
    animatePage: function() {
        if (this.pageAnimated == false) {
            this.pageAnimated = true;
        }
    },




    unAnimateContent: function(oldHref, newHref) {
        if (this.pageType[newHref] != this.pageType[oldHref]) {
            eval('counton.changeType(\'' + this.pageType[newHref] + '\')');
        }
        if (oldHref == '/gallery.aspx') {
            //unAnimateGallery();
        }
        else
            if (oldHref == '/process.aspx') {
            //unAnimateProcess();
        }
        else if (oldHref == '/services.aspx') {
            //unAnimateService();
        }
        else if (oldHref == '/home.aspx' || oldHref == '/partners.aspx') {
            //unAnimateContentPage();
        }
        else if (oldHref == '/contact.aspx') {
            //$('div#detBlock div#galleryContent #contactDetails').remove();  
            //$('div#subTitle').html('');      
        }
    },


    unAnimatePage: function() {
        this.pageAnimated = false;
        //other code
    },


    /*****************************end animate section *****************************/

    setTitle: function(title) {
       // if (typeof (title) != "undefined" && title != "") {
       //     document.title = counton.Title+' - ' + (title.toString().substr(0, 1)).toUpperCase() + title.toString().substr(1);
       // }
    },

    changeType: function(type) {
        counton.log('changeType: type: ' + type + '  ', "page");
        counton.log('pagetype finished', "page");
    },



    loading: function(isLoading) {
        //TODO loading functionality 
        /*  
        if (isLoading)
        {
        $("body").append('<div id="overlay" style="display:none;position:absolute;top:0;height:100%;width:100%;background-color:transparent;opacity:0.5;filter:alpha(opacity=50);z-index:1000;left:0px;"></div>');
        $("div#loader").fadeIn(100);
        $('div#overlay').fadeIn(300);
        }
        else
        {
        $("div#loader").fadeOut("slow");
        $("div#overlay").remove();
        }*/
    },

    assuranceInterval: 0,
    assuranceCnt: 0,
    assurance: function(len, act) {
        this.assuranceCnt++;
        if (true) {
            act();
            /*
            Usage:
            $(document).bind('event', 
            function ()
            {
            assuranceInterval = setInterval('assurance(4,function() {})',100);    
            });
            */
        }
        else {
            clearInterval(assuranceInterval);
        }
    },

    log: function(value, level, objs) {
        if (typeof (console) != "undefined") {
            //console.log("level: " +  level + " counton.debug: " + counton.debug + "\t\t" + counton.debug.join().indexOf(level));
            if (counton.debug.join().indexOf(level) >= 0) {
                var date = new Date();
                if (typeof (objs) == "object") {
                    var fval = "";
                    for (var i = 0; i < objs.length; i++) {
                        fval += objs[i].toString() + ":  " + eval(objs[i]) + "  ";
                    }
                    console.log(date.toTimeString().substr(0, 8) + "\t" + value + " " + fval);
                }
                else {
                    var date = new Date();
                    console.log(date.toTimeString().substr(0, 8) + "\t" + value);
                }
            }
        }
    },

    loadCustom: function(href) {
    },
    CustomDropDown:
    {
    loadCustomDropDown: function(klass){
        $(klass + ' li:first').css('padding-top','20px');
        $(klass).click(function() {
            $(klass + ' li').toggle();
        });
        $(klass).hover(function() { counton.CustomDropDown.hover = true;},function() { counton.CustomDropDown.hover = false;});
        $('body').click(function() {
            if (!counton.CustomDropDown.hover)
            {
               $(klass + ' li').hide();
            }
        });
    },
    
    hover: false
    },
    
    loadIframe: function(href, klass) {
        var iframHtml = '<div id="' + klass + '" style="display: block;" class="' + klass + '" marginheight="0px" marginwidth="0px" frameborder="0"> <iframe  marginheight="0px" marginwidth="0px" frameborder="0" name="wcc_iframe" src="' + href + '"></iframe></div>';
        counton.log("loadiframe { iframehtml : " + iframHtml + " href: " + href + " klass: " + klass, "page");
        return iframHtml;
    },

    getUrlFromFunction: function(url, functionCall) {
        var start = url.indexOf(functionCall) + functionCall.length + 1;
        url = url.substr(start, url.indexOf(");") - start - 1);
        return url;
    },
    customization:
    {
        fillPageCustom:function() {},
        fillPageCustomRem: function() {},
        func1:function(){},
        func2:function(){},
        func3:function(){},
        func4:function(){},
        func5:function(){},
        func6:function(){},
        func7:function(){},
        func8:function(){}
    },
anchorChanger: function(id)
{
		counton.log('loading according to anchor: '+id,"page");
                $('div.subMenuItem[num=_'+id+']').click();
                $('div.subMenuItem[num=_'+id+']').attr('id',$('div.subMenuItem[num=_'+id+']').attr('id')+'_hover')
},
anchorLoader: function(klass)
{
	$(klass).each(function() {
	if ($(this).attr('href').indexOf('#') > -1)
	{
		$(this).bind('onclick',function () {
		  if ($(this).attr('href').indexOf($.url.attr('path')) > -1)
		  {
		   counton.log('anchor changing','page');
		   counton.anchorChanger($.url.attr('anchor'));
		  }
		});
	}

	});
},
    //MENU
    menu: {
        lastHovered: "",
        loadMenuHovering: function(klass, hovering, hoveringSelected, unHovering, unHoveringSelected) {
            //menu hovering
            $("div." + klass).hover(function() {
                if ($(this).attr('selected') != 'true' && $(this).attr('selectedMicro') != 'true') {
                    $(this).attr("id", $(this).attr("id") + "_hover");
                    if (typeof (hovering) == "function") {
                        hovering($(this));
                    }
                }
                else {
                    if (typeof (hoveringSelected) == "function") {
                        hoveringSelected($(this));
                    }
                }
            },
    function() {
        if ($(this).attr('selected') != 'true') {
            var id = $(this).attr("id");
            if (id.lastIndexOf('_') >= 0) {
                id = id.substr(0, id.lastIndexOf('_'));
            }
            $(this).attr("id", id);
            //removing extra
            if (typeof (unHovering) == "function") {
                unHovering($(this));
            }
        }
        else {
            if (typeof (unHoveringSelected) == "function") {
                unHoveringSelected($(this));
            }
        }
    });
        },
        loadMenuClicking: function(klass, clicking, unClicking, clickingSelected) {
            $("div." + klass).click(function() {
                //only if not selected
                $(this).attr('selectedMicro', 'true');
                if ($(this).attr('selected') != 'true') {
                    //set others to not selected
                    $("div." + klass + "[selected=true]").each(function() {
                        var id = $(this).attr("id");
                        id = id.substr(0, id.lastIndexOf('_'));
                        $(this).attr("id", id);
                        $(this).attr('selected', 'false');
                        //removing extra
                        if (typeof (unClicking) == "function") {
                            counton.log("loadMenuClicking unClicking", "menu");
                            unClicking($(this));
                        }
                    });
                    //select current
                    $(this).attr('selected', 'true');
                    $(this).attr('selectedMicro', 'false');
                    if (typeof (clicking) == "function") {
                        clicking($(this));
                    }
                }
                else {
                    clickingSelected($(this));
                }
            });
        },
        positionSubMover: function(jObj) {
            //alert(jObj.offset().left + ' ' + jObj.offset().top);
            //alert(jObj.attr('id'));
            if ($('div.menuItem[id$=hover]').length == 0 && $('div.menuItem[selected=true]').length == 0) {
                return;
            }

            if (jObj.attr('id') == 'whats_on_hover' || jObj.attr('id') == 'notice_board_hover' || jObj.attr('id') == 'contact_us_hover') {
                $('div.subMenuItem').css('float', 'right');
                $('div#subMenuMover').css('z-index', '0');

                var getMenuConst = function(selected) {
                    var menuConst = 0;
                    if ($('div.menuItem[id$=_hover][selected=' + selected + ']').attr('id') == 'whats_on_hover' || $('div.menuItem[id$=_hover][selected=false]').attr('id') == 'whats_on') {
                        menuConst = 200;
                    }
                    if ($('div.menuItem[id$=_hover][selected=' + selected + ']').attr('id') == 'notice_board_hover' || $('div.menuItem[id$=_hover][selected=false]').attr('id') == 'notice_board') {
                        menuConst = 271;
                    }
                    if ($('div.menuItem[id$=_hover][selected=' + selected + ']').attr('id') == 'contact_us_hover' || $('div.menuItem[id$=_hover][selected=false]').attr('id') == 'contact_us') {
                        menuConst = 235;
                    }
                    return menuConst;
                }
                var menuConst = getMenuConst("false");
                if (menuConst == 0) {
                    menuConst = getMenuConst("true");
                }
                //        931 - 0 - null - 709
                $('div#subMenuMover').css({ 'left': document.getElementById(jObj.attr('id')).offsetLeft + menuConst - jObj.width() - $('div#subMenuMover').width() + 'px' });
                counton.log("positionSubMover  " + jObj.attr('id') + "  css left: " + jObj.css('left') + " offset left: " + jObj.offset().left + " abs left: " + document.getElementById(jObj.attr('id')).offsetLeft + " - " + menuConst + " - " + $(jObj).width() + " - " + $('div#subMenuMover').width(), "menu");
                //$('div.menuItem[id$=_hover][selected=false]').width()
            }
            else {
                $('div.subMenuItem').css('float', 'left');
                counton.log('positionSubMover: jObj.id: ' + $(jObj).attr('id'), 'menu');
                $('div#subMenuMover').css({ 'left': document.getElementById(jObj.attr('id')).offsetLeft + 'px', 'z-index': '0' });
            }
        }
    },
    
    logout: function() {
        $.get("/umbraco/memberloggedin.aspx?logout=1", function(data) { delete data; });
        $('div#user').html('');
        $('head style#traders').remove();
        counton.login = {}

    },

    getImageUrlFromCss: function(cssImage) {
        return cssImage.substr(cssImage.indexOf('url(') + 4, cssImage.indexOf(')') - 4).replace(/"/g,'').replace(/'/g,'');
    },


    login: {},

    getLogin: function() {
        $.getJSON('/umbraco/memberloggedin.aspx', function(data) {
            if (typeof (data) != "undefined" && data.loginName.length != "") {
                if (data.id == 0) {
                    return "not logged in";
                }
                else {
                    return data;
                }
            }
            else {
                return "not logged in";
            }
        });
    },
    /*updateLogin: function() {
        $.getJSON('/umbraco/memberloggedin.aspx', function(data) {
            if (typeof (data) != "undefined" && data.loginName.length != "") {
                if (data.id == 0) {
                    counton.log('updatelogin: logged out: typeof data: ' + typeof (data), 'ajax');
                    $('div#user').html('');
                    $('head style#traders').remove();
                    delete counton.login;
                }
                else {
                    counton.login = data;
                    $('head').append('<style id="traders" type="text/css">div.menuItem#traders{background-image:url(\'/images/traders_loggedin.gif\');} div.menuItem#traders_hover {background-image:url(\'/images/traders_loggedin_hover.gif\');}</style>');
                    counton.log('updatelogin: logged in: typeof data: ' + typeof (data), 'ajax');
                    $('div#user').html('You are logged in as: <strong>' + data.loginName + '</strong> <a style="margin-left:10px" href="#" onclick="counton.logout();">Logout</a>');
                }
            }

        });
    },*/
    currentHrefPageType: function() {
        return counton.pageType[$.url.attr('relative')];
    },
    //rdy
    ready: function() {
     
      if (this.centerPage)
        {
        this.posMiddle();
        }
     if (this.resizePage)
     {
        $(window).resize(function() {
            counton.onResize();
            });
     }
     counton.customization.fillPageCustom = function () {
          //customize resize
           counton.log('start custom fillPage','content');
           if ($(window).height() < counton.fillPageMin)
           {
                var k = $(window).height() - counton.fillPageMin;
                counton.log('k: '+k+ ' window.height '+$(window).height(),'content');
                $('div.botBack').css('bottom',k+'px');
           }
           else
           {
                $('div.botBack').css('bottom','0px');
           }
     };
     counton.customization.fillPageCustomRem = function (extraSpac) {
        counton.log('extraspace '+extraSpac,'content');
        if (extraSpac < -28)
        {
            $('div.botBack').css('bottom','-60px');
            return;
        }
        if ($(window).height() < counton.fillPageMin && $(window).height() - counton.fillPageMin > -32)
        {
            var k = $(window).height() - counton.fillPageMin;
            counton.log('k: '+k+ ' window.height '+$(window).height(),'content');
            $('div.botBack').css('bottom',k+'px');
        }
        else
        {
            $('div.botBack').css('bottom','0px');
        }
     };
     if (this.FillPage)
     {
        $(window).resize(function() {
            counton.fillPage(counton.fillElement,counton.fillExisting);
        });
        counton.fillPage(counton.fillElement,counton.fillExisting);
     }
     counton.TextBox.prepare('input#searchbox');

        this.loading(true);
        if ($.url.param('suc') == 1) {
            alert('Successfully sent!');
        }
        
        $('span a').each(function() {
            $(this).parent().attr('onclick',"window.location='"+$(this).attr('href')+"'");
        });

        //init menu
        $("div.menuItem,div.frontPageContent").each(function() {
            $(this).attr('selected', 'false');
            $.preloadImages(counton.getImageUrlFromCss($(this).css('background-image')));
            counton.log("preloading menu images: old: " + $(this).css('background-image') + " " + counton.getImageUrlFromCss($(this).css('background-image')), "menu");
        });
        //$.preloadImages("/images/traders_loggedin.gif", "/images/traders_loggedin_hover.gif","/images/slideMenu.png","/images/slideMenu_hover.png");
        var all = $.preloadCssImages();
	var p = jQuery.makeArray(all);
        $(p).each(function() {
		var k = String(this).replace('url("','');
		k = k.replace("url('",'');
		$.preloadImages(k);
	});
	
        $("div.menuItem,div.subMenuItem").each(function() {
            //fix menu id's
            $(this).attr('id').replace(' ', '_');
        });

        //$("div.subMenuItem[parent=traders]").bind('click',function () {
        //        if (typeof(counton.login.id) == "undefined" || counton.login.id == 0)
        //        {
        //            counton.ajaxGoto('/members/static/login.aspx');
        //            counton.log("submenuitem redirected traders if not logged in","menu");  
        //            return false;
        //        }
        //    });

       
        //preload images
        //$.preloadImages("","","","");

        if (counton.useAjax)
        {
            $(counton.ajaxElements).attr('href','#');
            $(counton.ajaxElements).parent().attr('href','#');
        }
        //menu management
        this.menu.loadMenuClicking("menuItem",
function(p) {
    //on clicking 
    //set current to default
    $('div.subMenuItem').each(function() {
        if ($(this).css('display') == "block") {
            $(this).attr('default', 'true');
        }
        //remove submenu selected
        if ($(this).attr('selected') == 'true') {
            $(this).attr('selected', 'false').removeClass('hover');
        }
    });
},
function(p) {
    //on offclicking
    //unset default
    $('div.subMenuItem').attr('default', 'false');
}, function() {
    return;
});

this.menu.loadMenuHovering('menuItem',
function(p) {
    //hovering
    $('div#menuItemSlide[num='+$(p).attr('num')+']').css('display','block');
    
    //$('div.subMenuItem[parent=' + counton.menuOptionsB[counton.getAjaxHref(p.attr('onclick'))] + ']').css('display', 'block');
    counton.log('menuItem hovering parent = ' + counton.menuOptionsB[counton.getAjaxHref(p.attr('onclick'))], "menu");
    counton.menu.lastHovered = counton.menuOptionsB[counton.getAjaxHref(p.attr('onclick'))];
},
function(p) {
    //hoveringselected
    //$('div.subMenuItem[parent=' + counton.menuOptionsB[counton.getAjaxHref(p.attr('onclick').toString())] + ']').css('display', 'block');
    //$('subMenuItem[default=true]').css('display','block');
    //counton.menu.lastHovered = counton.menuOptionsB[counton.getAjaxHref(p.attr('onclick').toString())];
},
function(p) {
    //on unhover
    $('div#menuItemSlide[num='+$(p).attr('num')+']').css('display','none');
},
function(p) {
    //on selected unhover
    $('div#menuItemSlide[num='+$(p).attr('num')+']').css('display', 'none');
}
);


        
          //move css menu li to above menu
        $('li.headlink ul li:nth-child(1)').each(function () {
            var offset = $(this).parent('#menuItemSlide').height();
            counton.log("menu offset:"+offset,'menu');
            $(this).css('margin-top','-'+offset+'px');
            setTimeout("$('head').append('<style>li.headlink ul{display:none;}</style>')",'10');
        });
        
        $('li.headlink ul li:nth-child(1)').each(function () {
            var offset = $(this).parent('#menuItemSlide').height();
            counton.log("menu offset:"+offset,'menu');
            $(this).css('margin-top','-'+offset+'px');
            setTimeout("$('head').append('<style>li.headlink ul{display:none;}</style>')",'10');
        });
        $('li.headlink ul:first').css('margin-left','-70px');
        
        //submenu management
        $('div.subMenuItem').each(function() { $(this).css('width', $(this).width() + 10); });
        var hover = function(p) { $(p).addClass('hover'); counton.log("submenu hover adding", "menu"); }
        var hoverClick = function(p) {
            $(p).addClass('hover').attr('selected', 'true');
            var num = $(p).attr('num');
            $('div#contentItem[num]').hide();
            if ($('div#contentItem[num='+num+']').length ==0)
            {
            counton.log("not found","menu");
            }
            $('div#contentItem[num='+num+']').show();
            $('div#contentItem[num='+num+']').show();
            counton.log("number:"+num, "menu");
            counton.log("submenu hover clicking", "menu");
        }
        var unhover = function(p) { if ($(p).attr('selected') != 'true') { $(p).removeClass('hover'); counton.log("submenu hover removeing", "menu"); } };
        
        this.menu.loadMenuClicking("subMenuItem", hoverClick, unhover, function() { });
        this.menu.loadMenuHovering("subMenuItem", hover, hover, unhover, unhover);





        //ld
        /************************************************* PAGES LOADING ***********************************************/
        //set the common pagetype function 
        counton.pageTypeCommonFunction = function() {
            //what you want to happen for every pagetype before the rest
            counton.log('execute common pagetype','page');
            $('ul#menuItemSlide').hover(function() { $(this).parent().find('div.menuItem').addClass('hover')},function() {$(this).parent().find('div.menuItem').removeClass('hover') });
            
            //font changes
            counton.log('loading font changes');
            counton.changeFont('div#fontButtons div','p,ul li',1.2);
            counton.changeFont('div#fontButtons div','div.subMenuItem',1.1);
            
            //search
            $('div.searchbutton').click(function() {
                var searchVal = $('input.searchbox').val();
                if (searchVal == null || searchVal == "" || searchVal == "Search")
                {
                    alert('Please enter keywords to search for');
                }
                else
                {
                    counton.log('redirecting:'+'/search.aspx?search='+escape(searchVal),'page');
                    window.location = '/search.aspx?search='+escape(searchVal); 
                }
             });
        };
        
        //load pagetypes custom
         $('a.customPageType').each(function() {
            if ($(this).attr('href') != "") {
                
                
                var url = $(this).attr('href');
                
                if (url.indexOf('#') > 0)
                {
                    url = url.substr(0,url.indexOf('#'));
                }
                
                }
                if (typeof($(this).attr('parent')) != "undefined" && $(this).attr('parent') != '')
                {
                    var title = $(this).attr('parent') + ' - ' + $(this).text();
                }
                else
                {
                    var title = $(this).text();
                }
                counton.menuOptionsB[url] = title;
                counton.menuOptions[title] = url;
                counton.pageType[url] = $(this).attr('type');
                counton.log("loading custom page types: url: " + url + " title: " + title + " type: " + $(this).attr('type'), "menu")
            
        });
        
        //load pagetypes and titles from menu
        $('div.menuItem,div#slideMenuItemDiv,div.footerMenu,div.logoLink').each(function() {
            if ($(this).attr('onclick') != "") {

                if (typeof($(this).attr('onclick')) != "undefined")
                {
		try {
                var url = counton.getUrlFromFunction($(this).attr('onclick').toString(), 'counton.loadSubPage(');
		}catch(e){}
                if (url.indexOf('#') > 0)
                {
                    url = url.substr(0,url.indexOf('#'));
                }
                
                }
                if (typeof($(this).attr('parent')) != "undefined" && $(this).attr('parent') != '')
                {
                    var title = $(this).attr('parent') + ' - ' + $(this).text();
                }
                else
                {
                    var title = $(this).text();
                }
                counton.menuOptionsB[url] = title;
                counton.menuOptions[title] = url;
                counton.pageType[url] = $(this).attr('type');
                counton.log("loading subMenuItem page types: url: " + url + " title: " + title + " type: " + $(this).attr('type'), "menu")
            }
        });
        
        
//        $('div.menuItem').each(function() {
//            if ($(this).attr('onclick') != "") {
//                var url = counton.getUrlFromFunction($(this).attr('onclick').toString(), 'counton.ajaxGoto(');
//                var title = $(this).attr('id').replace('_', ' ');
//                //        title = title.substr(0,1).toUpperCase() + title.substr(1,title.length);
//                counton.menuOptionsB[url] = title;
//                counton.menuOptions[title] = url;
//                counton.pageType[url] = $(this).attr('type');
//                counton.log("loading menuItem page types: url: " + counton.menuOptions[title] + " title: '" + counton.menuOptionsB[url] + "' type: " + $(this).attr('type'), "menu")
//            }
//        });


        //assign pagetype:functions 
        //initialise all    
        //for(p in counton.pageType
        //specific
        counton.pageTypeFunctions['FrontPage'] = function(href,html) {
            counton.CustomDropDown.loadCustomDropDown('ul#dropdown');
	    if ($('div.jScrollPaneContainer').length < 1) {
                $('div#wcccontent').jScrollPane({ showArrows: true, scrollbarWidth: 21, margin: 20 });
                $('div.jScrollPaneContainer').css({ 'top': '192px', 'left': '37px' });
            }
	    counton.log('starting auto scrolling','page');
	    counton.scrollInterval = setInterval('counton.scrollableApi.next()',6000);
        };
        counton.pageTypeFunctions['Search'] = function (href,html) {
        };
        counton.pageTypeFunctions['ContentPage'] = function(href, html) {
            if (html.length != 0) {
                $('div#mainContent').html($(html).find('div#mainContent').html());
                counton.log("content page animation", "page", ["contentPage.backgroundImage"]);
                counton.log('form ajaxifying', "ajax");
            }
            //check url #
            counton.log('length:'+$('div.subMenuItem:first').length,"page");
            if ($.url.attr('anchor') != null && $.url.attr('anchor') != '')
            {
                $('div.subMenuItem[num=_'+$.url.attr('anchor')+']').click();
                $('div.subMenuItem[num=_'+$.url.attr('anchor')+']').attr('id',$('div.subMenuItem[num=_'+$.url.attr('anchor')+']').attr('id')+'_hover')
            }
            else
            {
                $('div.subMenuItem:first').click();
                $('div.subMenuItem:first').attr('id',$('div.subMenuItem[num=_'+$.url.attr('anchor')+']').attr('id')+'_hover')
            }

		//create onclick events for anchors
	    //counton.anchorLoader('div#slideMenuItemDiv a');
            $('div#slideMenuItemDiv').each(function() {
    $(this).click(function() {
 counton.log('clicking submenu','page');

if ($(this).children().attr('href').indexOf($.url.attr('path')) > -1)
     {
	   counton.log('anchor changing','page');
	   var url = $(this).children().eq(0).attr('href');
	   var anchor = url.substr(url.indexOf('#')+1);	
	   counton.anchorChanger(anchor);
     } });
});
            
            //might use scrollpane
            counton.log('setting jscrollpane to wcccontent', 'page');
            if ($('div.jScrollPaneContainer').length < 1) {
                $('div#wcccontent').jScrollPane({ showArrows: true, scrollbarWidth: 21, margin: 20, animateInterval:100,animateStep:1 });
                $('div.jScrollPaneContainer').css({ 'top': '192px', 'left': '37px' });
            }
        }
        counton.pageTypeFunctions['MasterContentPage'] = counton.pageTypeFunctions['ContentPage'];

        counton.pageTypeFunctions['ContactUs'] = function(href, html) {
		$('textarea').attr('rows','5').attr('cols','50');
		counton.log('moving over column','page');
		$('ol').after('<ol id="secondCol"></ol>');
		$('li.email_li,li.phone_li,li.fax_li,li.enquiry_li').appendTo('ol#secondCol');
        }
        counton.pageTypeFunctions['RequestQuote'] = function(href, html) {
		$('textarea').attr('rows','5').attr('cols','50');
		$('input[type=checkbox]').next().hide();
		$('input[type=submit]').hide().after('<input type="button" style="float:right;margin-right:120px;" id="btnSubmit" value="'+$('input[type=submit]').val()+'"></input>');
		$('input#btnSubmit').bind('click',function() {
			
			if ($('input[id$=email]').val() == '' && $('input[id$=phone]').val() == '' && $('input[id$=fax]').val() == '')
			{
				alert('Please enter at least an email address, phone or fax number');
			}
			else
			{
			 	$('input[type=submit]').click();
			}
		});
		counton.log('moving over column','page');
		$('ol').after('<ol id="secondCol"></ol>');
		$('.Doc2Form').css({'width':'700px','height':'475px'});
		$('li.servicelevel_li,li.phone_li,li.fax_li,li.email_li,li.currentissues_li,li.additionalcomments_li,li.marketingmaterial_li').appendTo('ol#secondCol');
        }
        
        counton.pageTypeFunctions['Contact FormWWC'] = function(href, html) {
            if (html != '') {
                $('div#mainContent').html(html);
            }

            counton.log('setting jscrollpane to wcccontent', 'page');
            //            if ($('div.jScrollPaneContainer').length < 1) {
            //                $('div#wcccontent').jScrollPane({ showArrows: true, scrollbarWidth: 21, margin: 20 });
            //                $('div.jScrollPaneContainer').css({ 'top': '192px', 'left': '37px' });
            //            }
            $('input.button').bind('click', function() { $('div#wcccontent').animate({ 'scrollTop': 0 }) }).show();
            $('div#mainContent').css('background-image', 'url(' + contentPage.backgroundImage + ')');
        }
        

        //load custom
        counton.loadCustom = function(href) {
            counton.log("loadCustom href: " + href, "page");
        }
        
        
        
        //load the common pagetype function 
        counton.pageTypeCommonFunctionLoad();
        counton.log('loaded common page type function','page');
        
        //load this pagetype
        counton.animateContent(counton.getRelativeUrl(),'');
        
        
        //this.loadImage(backgroundImages[selected]);
        /****************************************************** END PAGES LOADING ************************************/
        this.loading(false);
        //end of counton.ready
    },


    loadSubPage: function(href) {
        counton.log("loadSubPage { href:" + href + " }", "page");
        if ($('a[href=' + href + ']').length > 0) {
            document.location = href;
        }
        counton.ajaxGoto(href);
    }

}


//outside counton
$.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    $("<img>").attr("src", arguments[i]);
  }
}
//fire countonready
$(document).ready(function () {
counton.ready();
});




function MM_findObj(n, d) { //v4.01
        var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
               d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
        if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
        for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
        if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
        var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
        if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
        var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function showHideLayer(_layer,_mode) {
        if (_mode == 'on') {
               document.getElementById("ctrlMenu_divSubNavServices").style.display = "block";
               //setTimeout("showHideLayer('off');",8000);
        } else {
               document.getElementById("ctrlMenu_divSubNavServices").style.display = "none";
        }
}



