var counton = {

    //all 
    //debug: ["menu","ajax","page","content"],
    debug: ["ajax", "page", "content", "menu"],

    /* page types:
    ContentPage

details_block_only
    sub_block_only
    both_blocks
    */

    pageTypeFunctions: {},


    pageType: { '/privacy-policy.aspx': 'content' },
    menuOptions: {},
    menuOptionsB: {},


    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;
    },

    posMiddle: function() {
        var height = $(window).height();
        var extraSpace = height - $('.oneColFixCtrHdr #container').height();
        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() {
        $('#mainContent').css('height', $(window).height() - ($('#footer').height() + $('#header').height() + $('#menu').height()));
        //this.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);
        }


        if (href == '/home.aspx') {
        }
        if (href == '/contact.aspx') {
            $('div#detBlock div#galleryContent div#content').html(html);
            var contactDetails = $('div#detBlock div#galleryContent div#content #contactDetails').html();
            $('div#detBlock div#galleryContent div#content #contactDetails').settitleremove();
            $('div#detBlock div#galleryContent').append('<div id="contactDetails">' + contactDetails + '</div>');
            $('div#subTitle').append('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Contact Details');
            $('div#subTitle').hide().show();
            $('textarea').attr('rows', '4');
            setTimeout("this.loading(false)", 600);
        }
        else if (href == '/gallery.aspx') {
            this.loading(false);
        }
        else if (href == '/process.aspx') {
            //put content into page 
            //$('div#nextPrev').after(html);
            //animateProcess();
            this.loading(false);
        }
        else if (href == '/services.aspx') {
            //put content into page 
            //$('div#nextPrev').after(html);
            //animateServices();
            this.loading(false);
        }
        else if (href == '/partners.aspx') {
            //animateLinks(html);
            this.loading(false);
        }
    },


    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 = 'Williamstown Chamber of Commerce - ' + (title.toString().substr(0, 1)).toUpperCase() + title.toString().substr(1);
        }
    },

    changeType: function(type) {
        counton.log('changeType: type: ' + type + '  ', "page");
        //var login = counton.getLogin();
        //counton.log('counton.login name ' + login['name'] + ' ' +login['806'] + ' ' + login['email']);
        if (type == 'ContentPage') {
            $('div#mainContent').css('background-image', 'url(' + contentPage.backgroundImage + ')');
        }
        else if (type == 'ContactUsRegisteredWCC') {
            counton.log('pagetype ContactUsRegisteredWCC', "page");
            $('input[id$=registered_name]').parent('li').hide(); //val(login['name']);
            $('input[id$=registered_surname]').parent('li').hide(); //val(login['806']);
            $('input[id$=registered_email]').parent('li').hide(); //val(login['email']);
            assuranceInterval = setInterval("counton.assurance(4,function() {\
            if (counton.login['name'] != '')\
            {\
                $('input[id$=registered_name]').val(counton.login['name']);\
                $('input[id$=registered_surname]').val(counton.login['806']);\
                $('input[id$=registered_email]').val(counton.login['email']);\
            }\
        })", 1000);


        }
        else if (type == '') {

        }
        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) {
    },

    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;
    },

    //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);
    },


    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() {
        $(window).resize(function() {
            counton.onResize();
        });
        counton.onResize();
        this.loading(true);
        if ($.url.param('suc') == 1) {
            alert('Successfully sent!');
        }

        //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();
});
