if(!window.console) {
    window.console = {"log": function(msg) {} };
}

$(function() {    
    
    var HXT = {
        is_replaying: true,
        PART_SEP: '&',
        VAR_SEP: '/',
        replay_callbacks: {},
        CKEY: "location-hash-",
        vars: {},
        INITIAL_HASH_VAL: "/frontofhouse",
        last_hash: location.hash
    };

    HXT.record = function(hash_var, hash_section_idx, hash_var_idx, clear_following, force) {       
        if(!HXT.is_replaying) {
            var location_hash = location.hash.substr(2);
            
            var hash_sections = location_hash.split(HXT.PART_SEP);       
            var hash_section;        
        
            hash_section = hash_sections[hash_section_idx];        
        
            var hash_vars = [];
            if(hash_section) {
                hash_vars = hash_section.split(HXT.VAR_SEP);           
            }
                 
            if(clear_following) {
                hash_vars.splice(hash_var_idx+1, hash_vars.length-(hash_var_idx+1));
            }
            
            if(hash_var === null) {
                delete hash_vars[hash_var_idx];
            } else {
                hash_vars[hash_var_idx] = hash_var;
            }
        
            var new_hash_section = hash_vars.join(HXT.VAR_SEP);                
            
            if(new_hash_section.length > 1 && new_hash_section.charAt(new_hash_section.length-1) !== '/') {
                hash_sections[hash_section_idx] = new_hash_section;
            } else if(new_hash_section.length > 1) {
                hash_sections[hash_section_idx] = new_hash_section.substring(0, new_hash_section.length-1);
            }
            
            location.hash = "/"+hash_sections.join(HXT.PART_SEP);
            
            HXT.last_hash = location.hash;
            
            
        }
    };

    HXT.save_hash = function() {
        $.cookie(HXT.CKEY + location.pathname, location.hash);
    };     
    
    HXT.get_saved_hash = function() {
        return $.cookie(HXT.CKEY + location.pathname);
    };
    
    HXT.restore_hash = function() {
        var saved_hash = HXT.get_saved_hash();
        if(location.hash.substr(1) === '' && saved_hash) {
            location.hash = HXT.get_saved_hash();
            $.cookie(HXT.CKEY + location.pathname, null);
            HXT.last_hash = saved_hash;
        }
        
    };

    HXT.replay_callback = function(id) {
        if(HXT.replay_callbacks[id]) {
            HXT.is_replaying = true;
            HXT.replay_callbacks[id]();
            delete HXT.replay_callbacks[id];
            HXT.is_replaying = false;
        }
    };

    HXT.replay = function() {        
        
        HXT.is_replaying = true;
        if(location.hash.substr(1)) {
            
            var sections = location.hash.substr(2).split(HXT.PART_SEP);
        
            var show_main_menu = true;
            var image_area_section = sections[0];
            var main_menu_section = sections[1];
        
            // playback the image area history
            if(image_area_section) {
                var h = image_area_section.split(HXT.VAR_SEP);
            
                if(h[0]) {
                    var vid = h[0];
                    goto_place(vid);                           
                }
            
                if(h[1]) {
                    var dotid = h[1];
                    show_main_menu = false;    
                    HXT.replay_callbacks["#dots"] = function() {
                        var dot = $("#"+dotid);
                        dot.click();                                
                    };                                                 
                }                
            }
        
            // playback the main menu history
            if(main_menu_section && show_main_menu) {
                var h = main_menu_section.split(HXT.VAR_SEP);
                
                main_menu_is_visible = h[2] ? true : false;
            
                if(h[0]) {                    
                    var p1_id = h[0];         
                    HXT.replay_callbacks["#menu-where"] = function() {                             
                        $("#"+p1_id).click();
                        $("#menu-where").scrollTo("#"+p1_id);                         
                    }       
                    $("#navbar a").mouseover();
                }
            
                if(h[1]) {
                    var t1_id = h[1];         
                    HXT.replay_callbacks["#menu-what"] = function() {                            
                        $("#"+t1_id).click();
                        $("#menu-what").scrollTo("#"+t1_id);
                    };    
                }
            
                if(h[2]) {
                    var c1_id = h[2];         
                    HXT.replay_callbacks["#menu-who"] = function() {                                              
                        $("#"+c1_id).addClass("hover");
                        $("#menu-who").scrollTo("#"+c1_id);                    
                    };
                    
                    HXT.replay_callbacks["#menu-who-dot"] = function() {                                                  
                        $("#"+c1_id).addClass("hover");
                        $("#menu-who-dot").scrollTo("#"+c1_id);                    
                    };
                }
            }
        } else if(!location.pathname || location.pathname === '/') {       
            location.hash = HXT.INITIAL_HASH_VAL;
            $("#ia-pager ul li a:first").click(); 
        }
     
        HXT.is_replaying = false;
        
        HXT.interval_id = setInterval(HXT.watch_hash, 500);
    };
    
    HXT.watch_hash = function() {               
        if(HXT.last_hash !== location.hash) {
            clearInterval(HXT.interval_id);
            HXT.last_hash = location.hash;
            HXT.replay();
        }
    };
    
    HXT.reset = function() {
        // do whatever you need to do to reset the Ajax junk in your thing
        
    };
    
    
    
    setInterval(function() {
        //HXT.replay();
    }, 5000);

    var LOADER_PATH = THEME_PATH + "/images/loaders";
    var PLACE_WIDTH = 980;
    
    var places = [
        {
            'frontofhouse': 'Front of House',
            'entertainmentroom': 'Entertainment Room',
            'familyroom': 'Family Room',            
            'garage': 'Garage'
        },
        {
            'bathroom': 'Bathroom',
            'barbecue': 'Barbecue',
            'bedroom': 'Bedroom',
            'diningroom': 'Dining Room'
        },        
        {
            'kidsroom': 'Kid\'s Room',
            'kitchen': 'Kitchen',
            'laundryroom': 'Laundry Room'
        },
        {
            'livingroom': 'Living Room',
            'patio': 'Patio',
            'sunroom': 'Sunroom'
        }
    ];
    HXT.vars.places = places;
    
    var places_tids = {
        'bathroom':1,
        'barbecue':14,
        'bedroom':2,
        'diningroom':4,
        'entertainmentroom':5,
        'familyroom':6,
        'frontofhouse':3,
        'garage':7,
        'kidsroom':8,
        'kitchen':9,
        'laundryroom':10,
        'livingroom':11,
        'patio':12,
        'sunroom':13
    };
    
    var logos = {};
    var current_area_link;
    var last_ia_image;
    
    var zone = $("#image-area");
    var zint = $("#zint");
    
    var nb_timer;
    var dot_delta = 0;
    var current_dot;
    
    var loader_where = $('<img src="' + LOADER_PATH + '/where.gif" class="loader" />');    
    var loader_what = $('<img src="' + LOADER_PATH + '/what.gif" class="loader" />');
    var loader_who = $('<img src="' + LOADER_PATH + '/who.gif" class="loader" />');
    var dot_menu = $('<img src="' + LOADER_PATH + '/dot-menu.gif" class="loader" />');
    
    var panels = $(
        '<div class="dd-menu" id="menu-where"></div>'+
	    '<div class="dd-menu" id="menu-what"></div>'+
	    '<div class="dd-menu" id="menu-who"></div>');
	    
	$("#page").append(panels);
	
	var logo_dialog = $(
	    '<div id="sponsor-logo" class="rounded">' +
	    '<img id="sponsor-logo-pointer" src="' + THEME_PATH +  '/images/logo-pointer.png" alt="logo"/>' +
	    '<img id="sponsor-logo-img" src="#sponsor-logo#" alt="logo"/><p>sponsored link</p></div>');
	
	$("body").append(logo_dialog);
	
	var ia_dialog = $('<div id="ia-dialog"><h2 class="title">#title#</h2></div>');
	var ia_tooltip = $('<div id="ia-tooltip"><h2 class="title">#title#</h2></div>');
	$("body").append(ia_dialog);
	$("body").append(ia_tooltip);
	
	var place_lists = [];
	$(places).each(
	    function(i) {
	        
	        var places_set = places[i];
	        
	        var places_list = $('<ul class="place-list"></ul>');	
	        for(var p in places_set) {
	            
    		    var li = $("<li></li>");		    
    		    var link = $('<a href="#"></a>');
    		    link.attr("href", p);
    		    link.attr("id", p);
    		    link.html(places_set[p]);
    		    li.append(link);		    
    		    places_list.append(li);
    		    
    	    }
    	    place_lists[i] = places_list;
    	    $("#ia-pager").append(places_list);    	    
        }
    );    
    
    $("#ia-pager ul").css("left", 980);      
    
    var selected_arrow = $('<img id="ia-pager-select-arrow" />');
    selected_arrow.attr("src", THEME_PATH + "/images/ia-selected-arrow.png");
    $("body").append(selected_arrow);
    $("#ia-pager ul li a").click(ia_pager_click);
    //$("#ia-pager ul").hide(); 
    $("#ia-pager ul:first").show();
    
    var current_place_set = $("#ia-pager ul:first"); 
    var cps_x = (980 / 2) - (current_place_set.width() / 2);
    current_place_set.css("left", cps_x);   
    //$("#ia-pager ul li a:first").click();    
    
    $("#search input.go,#footer a img,#ia-pager img, .visit-company-link img").imageRoll();
    $("#search input.q").peekABooField();
    
    if(!$.browser.msie) {
        $("div.rounded,.tabs a").corners();
        $(".cbody, #ad-sidebar").corners("15px");
        $("#ia-dialog,#ia-tooltip").corners("15px"); 
    }  

    $("#ia-dialog, #ia-tooltip, div.dd-menu, #sponsor-logo").hide();
     
    $("#navbar a").hover(
        function(e) {            
            nb_clear_timer();            
            dot_close();
            
            $("#qtvid").visible(false);
            
            if($(".menu-opened").length) {
                $(".menu-opened").slideDown();
                $(".menu-opened .selected").parents(".menu-opened").scrollTo(".selected");
                HXT.replay_callback("#menu-where");
                return;
            }            
            
            if(!$(this).data("am_visible")) {
                if($("#menu-where ul").children().length == 0) {
                    $.getJSON("/xhr/places.php", xhr_places);
                    $("#menu-where").empty();
                    $("#menu-where").append(loader_where);
                    loader_where.hide().fadeIn();
                }                
                
                $("#menu-where").slideFadeDown();                
                $(this).data("am_visible", true);                               
            }    
        }, 
        function(e) {            
            nb_set_close_timer();            
        }
    ).click(function(){ $(this).blur(); return false;});
    
    function nb_close() {
        nb_clear_timer();
        $("#qtvid").visible(true);
        $("#navbar a").data("am_visible", false);        
        $(".dd-menu").slideUp();
    }
    
    function nb_clear_timer() {        
        clearTimeout(nb_timer);
    }
    
    function nb_set_close_timer() {
        nb_clear_timer();
        nb_timer = setInterval(nb_close, 800);
    }
    
    if($("#ia-pager-prev img").length) {
        $("#ia-pager-prev img").attr("src", $("#ia-pager-prev img").attr("src").replace(".png", "-off.png"));
    }
    
    $("#ia-pager-more").click(function(e) {        
        e.preventDefault();        

        var next = current_place_set.next("ul");
        
        if(next.is("ul")) {
            var pw = PLACE_WIDTH;
            
            current_place_set.animate({'left':-pw, "opacity":  1});
            current_place_set = next;       
            var x = (pw / 2) - (current_place_set.width() / 2);            
            
            current_place_set.animate({'left': x, "opacity": 1}, null, null, pager_anim_done);
            
            // analytics throws errors here for some reason
            try {
                if(!HXT.is_replaying) {
                    next.find("a:first").click();        
                }
            } catch(err) { }
            
            $("#ia-pager-prev img").attr("src", $("#ia-pager-prev img").attr("src").replace("-off.png", ".png"));
        } 
        if(!next.next().is("ul")) {
            // disable the "more" button
            // and enable the prev button if it's not enabled
            var img = $(this).find("img");
            var img_src = img.attr("src");
            img.attr("src", img_src.replace("-over.png", "-off.png"));
        }        
        return false;
    });
    
    $("#ia-pager-prev").click(function(e) {        
        e.preventDefault();         
        
        var next = current_place_set.prev("ul");
        
        if(next.is("ul")) {
            var pw = PLACE_WIDTH;//$("#ia-pager").width();
            
            current_place_set.animate({'left':pw, "opacity":  1});
            current_place_set = next;
            var x = (pw / 2) - (current_place_set.width() / 2);
            
            current_place_set.animate({'left': x, "opacity":  1}, null, null, pager_anim_done);
            
            try {
                if(!HXT.is_replaying) {
                    next.find("a:first").click();        
                }
            } catch(err) { }
            
            $("#ia-pager-more img").attr("src", $("#ia-pager-more img").attr("src").replace("-off.png", ".png"));
        }
        
        if(!next.prev().is("ul")) {
            // disable the prev button
            var img = $(this).find("img");
            var img_src = img.attr("src");
            img.attr("src", img_src.replace("-over.png", "-off.png"));
        }        
        return false;
    });
    
    function pager_anim_done() {
        var arr = $("#ia-pager-select-arrow");
        arr.show();
        var offs = current_area_link.offset();
        arr.css("top", offs.top - 12);
        arr.css("left", offs.left + current_area_link.width() / 2 + arr.width() / 2);
    }
    
    function ia_pager_click(e) {
        e.preventDefault();
        var img_id = this.id + "_image";
           
        $("#ia-dialog").hide();  
        var me = $(this);
        $("#ia-pager ul li a").removeClass("selected");
        me.addClass("selected");
        var arr = $("#ia-pager-select-arrow");
        arr.show();
        var offs = me.offset();
        arr.css("top", offs.top - 12);
        arr.css("left", offs.left + me.width() / 2 + arr.width() / 2);
        //me.blur();
        
        var img = $("#"+img_id);
        if(!$("#"+img_id).attr("src")) {
            img = $("<img class='place'/>");
            img.attr("src", THEME_PATH + "/images/places/" + this.id + ".jpg");
            img.attr("id", img_id);
            img.attr("width", 980);
            img.attr("height", 557);
            $("#zint").append(img);
        } 
        
        img.hide();        
        
        if(last_ia_image) {
            last_ia_image.fadeOut("slow");
        }
        
        img.fadeIn();
        current_area_link = me;
        last_ia_image = img;
        
        get_data('/json/' + this.id + '.json');        
        
        nb_close();
        dot_close();
        
        HXT.record(this.id, 0, 0, true, true);      
        
        return false;
    }
    
    function goto_place(sid) {
        // Figure out if we're on the correct "image/photo" for this place
        var screen_id = 0;
        $.each(places, function(i) {           
           if(this[sid]) {
               screen_id = i;
               return false;
           }
        });
        
        var previous_set = current_place_set;
        current_place_set = place_lists[screen_id];
    
        $.each(place_lists, function(i) {
            if(i < screen_id) {
                place_lists[i].css("left", -980);
            } else {
                place_lists[i].css("left", 980);
            }
            //$(this).hide();
        });               
        
        var x = (PLACE_WIDTH / 2) - (current_place_set.width() / 2);                   
        current_place_set.animate({'left': x, "opacity":  1}, null, null, pager_anim_done);        
        current_place_set.find("#"+sid).click();
        
        var prev_img_src = $("#ia-pager-prev img").attr("src");
        //alert(screen_id);
        if(screen_id === 0 && prev_img_src.indexOf("-off.png") === -1) {
            $("#ia-pager-prev img").attr("src", prev_img_src.replace(".png", "-off.png"));
        } else if(screen_id > 0) {
            $("#ia-pager-prev img").attr("src", prev_img_src.replace("-off.png", ".png"));
        }
        
        var more_img_src = $("#ia-pager-more img").attr("src");
        if(screen_id === place_lists.length-1 && more_img_src.indexOf("-off") === -1) {
            $("#ia-pager-more img").attr("src", $("#ia-pager-more img").attr("src").replace(".png", "-off.png"));
        } else {
            $("#ia-pager-more img").attr("src", $("#ia-pager-more img").attr("src").replace("-off.png", ".png"));
        }
    }
    
    $(".dd-menu").hover(
        function() {            
            nb_clear_timer();
        },
        function() {            
            nb_set_close_timer();
        }
    );
    
    function xhr_places(data) {
        $("#menu-where").empty();
        $("#menu-where").addClass("menu-opened");
        
        var where_list = $("<ul></ul>");
        for(var i in data) {
            var place = data[i];
            var list_item = $('<li><a id="MMp1_' + place.vid + '" href="/xhr/things.php?vid=' + place.vid + '">' + place.name + '</a></li>');
            
            where_list.append(list_item);
        }
        $("#menu-where").append(where_list);
        
        $("#menu-where a").click(
            function() {
                $.getJSON(this.href, xhr_things);
                $("#menu-who").empty();
                $("#menu-where a").removeClass("selected");
                $(this).addClass("selected");
                nb_clear_timer(); 
                
                var moff = $("#menu-where").width();
                $("#menu-what").animate({"left": moff, "opacity": "show"}, "fast");
                $("#menu-what").empty();     
                $("#menu-what").append(loader_what); 
                loader_what.hide().fadeIn();                    
                 
                HXT.record(this.id, 1, 0, true);
                return false;
            }
        ).mouseover(
            function() {                
                nb_clear_timer();
            }
        );
        HXT.replay_callback("#menu-where");
    }
    
    function xhr_things(data) {        
        var menu = $("#menu-what");
        menu.addClass("menu-opened");
        
        menu.empty();
        var moff = $("#menu-where").width();              
        
        var what_list = $("<ul></ul>");
        for(var i in data) {
            var thing = data[i];
            var list_item = $('<li><a id="MMt1_' + thing.tid + '" href="/xhr/companies.php?tid=' + thing.tid + '">' + thing.name + '</a></li>');
            what_list.append(list_item);
        }
        
        menu.append(what_list);
        
        $("#menu-what a").click(
            function() {
                $.getJSON(this.href, xhr_companies_menu);
                $("#menu-what a").removeClass("selected");
                $(this).addClass("selected");
                nb_clear_timer();
                
                var moff = $("#menu-where").width() + $("#menu-what").width();
                $("#menu-who").animate({"left": moff, "opacity": "show"});
                $("#menu-who").find("ul,img").remove();
                $("#menu-who").append(loader_who); 
                loader_who.hide().fadeIn();
                
                HXT.record(this.id, 1, 1, true);            
                return false;
            }
        ).mouseover(
            function() {
                nb_clear_timer();
            }
        );
        
        HXT.replay_callback("#menu-what");
        
    }
    
    function xhr_companies_menu(data) {
        var menu = $("#menu-who");
        menu.addClass("menu-opened");
        menu.find("ul,img").remove();
        
        xhr_companies(data, menu, "MMc1_", function() { HXT.record(this.id, 1, 2); });
        
        HXT.replay_callback("#menu-who");
    }
    
    function xhr_companies_dot(data) {
        var menu = $("#ia-dialog");
        var iad_title = $("#ia-dialog h2.title");
        var title = current_dot.find("img").attr("alt");
        iad_title.text(title);                
        
        menu.find("ul,img").remove();
        
        xhr_companies(data, menu, "DMc1_", function() { HXT.record(this.id, 0, 2); });
        
        HXT.replay_callback("#menu-who-dot");
    }
    
    function xhr_companies(data, menu, prefix, click_func) {       
        var who_list = $("<ul></ul>");
        for(var i in data) {
            var who = data[i];
            var link_url = '/node/' + who.nid;
            var link = $('<a id="' + prefix + who.nid + '" href="' + link_url + '">' + who.title + '</a>');
            
            if(who.field_sponsor[0].value == 1) {
                link.attr("id", "spl_" + who.nid);
                logos[link.attr("id")] = who.field_logo[0];
                       
                link.addClass("sponsor");
                link.hover(logo_rollover, logo_rollout);
            }
            
            link.click(click_func);
            link.click(function() {
               HXT.save_hash();  
            });
            var list_item = $('<li></li>');
            list_item.append(link);
            who_list.append(list_item);
        }
        menu.append(who_list);
        
        menu.find("a").mouseover(
            function() {
                menu.find("a").removeClass("hover");      
                nb_clear_timer();
            }
        );         
    }

    function logo_rollover(e) {
        var logo = $(this);
        var src = logos[this.id].filepath.replace("/files/", "/files/imagecache/sponsor_logos/");
        $("#sponsor-logo-img").attr("src", "/" + src);        
        $(this).mousemove(logo_mousemove);        
        $("#sponsor-logo").show();
    }
    
    function logo_rollout(e) {
        $(this).unbind("mousemove", logo_mousemove);
        $("#sponsor-logo").hide();
    }
    
    function logo_mousemove(e) {
        $("#sponsor-logo").css("left", e.pageX + 46); 
        $("#sponsor-logo").css("top", e.pageY - 30);
    }

    
    function place_dot_helper(d,k) {
        var img_src = THEME_PATH + "/images/" + ($.browser.msie && $.browser.version <= 6 ? "livedot-ie6.png" : "livedot.png");
        var dot = $('<a href="/xhr/companies.php?vid=' + places_tids[current_area_link.attr("id")] + '&tid=' + escape(d.pid) + '" class="dot"><img src="' + img_src + '" class="dot" alt="' + d.pid + '" /></a>');
        dot.click(dot_click);
        dot.mouseover(dot_over).mouseout(dot_out);
        if(!$.browser.msie) {
            dot.css('opacity', .75);
        }
        zone.append(dot);
                
        dot.css("left", d.x - 16);
        dot.css("top", d.y - 16);
                
        dot.attr("id", k);
        
        data[k] = {
            "pid": d.pid,
            "x": d.x,
            "y": d.y
        };
    }
    
    function dot_over(e) {        
        var dot = $(this);
        
        var iad = $("#ia-tooltip");   
        var iad_title = $("#ia-tooltip h2.title");
        iad_title.html(dot.find("img").attr("alt"));     
        var x = dot.offset().left + 16;
        var y = dot.offset().top-6;
        
        var w = iad.outerWidth();
        var h = iad.outerHeight();
        
        iad.css("top", y-dot.outerHeight()-3);
        iad.css("left", x-w/2);        
        iad.stop(true,true).fadeIn();
    }
    
    function dot_out(e) {
        $("#ia-tooltip").stop(true,true).fadeOut();
    }
    
    function dot_click(e) {    
        e.preventDefault();        
        
        nb_close();
        dot_close();
        dot_out();
        
        current_dot = $(this);
        
        current_dot.css("z-index", 10000);
        
        $.getJSON(this.href, null, xhr_companies_dot);
        
        var iad = $("#ia-dialog");   
        var iad_title = $("#ia-dialog h2.title");
        iad_title.html("");     
        var x = current_dot.offset().left + 16;
        var y = current_dot.offset().top + 16;
        iad.css("top", y-120);
        iad.css("left", x);
        iad.find("ul").remove();
        iad.append(dot_menu);
        
        iad.hide().animate({"width": "show", "opacity":  "show"});
        
        var dot_img = current_dot.find("img");
        
        if(dot_img.attr("src").indexOf("-over.png") !== -1) {
            dot_img.attr("src", dot_img.attr("src").replace("-over.png", "-selected.png"));
        } else {
            dot_img.attr("src", dot_img.attr("src").replace(".png", "-selected.png"));
        }
        
        current_dot.unbind("click").unbind("mouseover").unbind("mouseout")
        current_dot.click(dot_close);        
        
        HXT.record(this.id, 0, 1, true);        
        
        return false;    
    }

    function dot_close() {                           
        $("#ia-dialog").stop(true,true).hide(); 
        if(current_dot) {
            current_dot.mouseover(dot_over).mouseout(dot_out);
            current_dot.css("z-index", 3);
            current_dot.unbind("click");
            current_dot.click(dot_click);            
            var dot_img = current_dot.find("img");
            dot_img.attr("src", dot_img.attr("src").replace("-selected.png", ".png"));  
            HXT.record(null, 0, 1, true);          
            current_dot = null;                    
        }        
        
        return false;         
    }
    
    function get_data_callback(d) {   
        clear_data();       
        for(var n in d) {
            place_dot_helper(d[n], n);
        }
        
        zone.find("a.dot img").imageRoll();
        
        HXT.replay_callback("#dots");
    }
    
    function clear_data() {
        zone.find("a.dot").remove();
        data = {};
        dot_delta = 1000;
    }
    
    function get_data(f) {        
        //clear_data();        
        $.getJSON(f, null, get_data_callback);
    }
    
    $(".howto li").each(
        function(i) {
            var c = (i+1);
            var n = $('<span class="num">' + c + ':</span>');
            $(this).prepend(n);
        }
    );
    
    HXT.restore_hash();
    HXT.replay();
        
});
