var groups = [ "geo", "rank", "listings", "inbound1", "social", "technical" ];

var techLoaded = false;
var searchenginesLoaded = false;
var rankLoaded = false;
var inboundLoaded = false;
var indexedLoaded = false;

var currentGroupIndex = -1;
var currentItem = -1;
var currentGroupItemsCount = -1;
var groupComplete = false;

var items = {
    "geo": 0,
    "rank": 0,
    "listings": 0,
    "inbound1": 0,
    "social": 0
};

var reportData = {};
var reportGroup = -1;

function queryReports(url) {
    if (currentGroupIndex != -1 && !groups[currentGroupIndex]) {
        //document.body.style.cursor = 'auto';
        return;
    }
    
    var params = {
        'url' : url,    
        'action': 'report',
        'lang': languageCode
    };
    
    //document.body.style.cursor = 'wait';
    
    var call = false;
    var nextGroup = groupComplete ? true : false;
    
    if (currentItem == -1) {
        currentItem = 0;
        call = true;
    } else if (currentItem < (currentGroupItemsCount-1)) {
        currentItem++;
        call = true;
    } else { // last item => next group   
        nextGroup = true;
        currentGroupItemsCount = -1;
        currentItem = 0;
    }
    
    if (currentGroupIndex == -1) { // ini
        currentGroupIndex = 0;
        call = true;
    } else if (nextGroup && currentGroupIndex < groups.length-1) {
        currentGroupIndex++;
        call = true;
    } else {
        // last group
    }
    
    if (groupComplete) {
        percent = 100; 
    } else if (currentItem == 0) {
        percent = 0;
    } else if (currentItem < (currentGroupItemsCount-1)) {
        percent = Math.round((new Number(currentItem)) * 100 / currentGroupItemsCount);
    } else {
        percent = 100; 
    }
    
    if (percent > 0) {
        var loader = $("#"+groups[currentGroupIndex]+"-box-loader div[class='text']");
        if (loader) {
            if (percent == 100) {
                loader.html(loadingLabel + "...");
            } else {
                loader.html(loadingLabel + "... " + percent + "%");
            }
        }
    }
    
    //console.log('query - currentItem='+currentItem+', currentGroup='+groups[currentGroupIndex]+' (count: '+currentGroupItemsCount+'), nextGroup='+nextGroup+', call='+call+', percent='+percent);
    
    if (call) {
        params.group = groups[currentGroupIndex];
        params.item = currentItem;
                
        if (params.group == 'rank') {
            $("#rank-box-loader").show();           
        } else if (params.group == 'listings') {
            $("#listings-box-loader").show();       
        } else if (params.group == 'inbound1') {
            $("#inbound1-box-loader").show();       
        }
        
        //TODO check timeout and errors
        
        $.getJSON(
            "/controller.php",
            params,
            function(data) {        
                if (data.success) {
                    groupComplete = (currentItem == data.data['groupItems']-1 || data.data['status'] == "full") ?
                        true : false;
                    
                    if (data.msg == 'syntax_error') {
                        // TODO alert('Malformed URL!');
                    } else if (data.msg == 'not_reachable') {
                        // TODO alert('URL not reachable! Please try again later!');
                    }
                    
                    for (var key in data.data) {
                        if (data.data[key] != undefined) {                      
                            var foo = data.data[key];
                            eval('reportData["'+key+'"] = foo;'); // ie shit...
                            //reportData[key] = foo;
                            if (key!="group" && key!="cacheHit" && key!="item" && key!="groupItems") {
                                if (key == 'web_archive_domain_age') {
                                    if (reportData[key]['msg']) {
                                        $("#domain_age").html(reportData[key]['msg']);
                                    } else {
                                        $("#domain_age").remove();
                                    }
                                } else if (key == 'lycos_inbound_links') {
                                    if (reportData[key]) {
                                        $("#lycos_inbound_links").html(reportData[key]);
                                    }
                                } else if (key == 'alexa_inbound_links') {
                                    if (reportData[key]) {
                                        $("#alexa_inbound_links").html(reportData[key]);
                                    }
                                } else if (key == "server_location") {
                                    if (!reportData[key]['server_location_msg']) {
                                        $("#geo-box").remove();
                                    } else {
                                        $("#"+key).html(reportData[key]['server_location_msg']);
                                    }
                                } else if (key == "yahoo_indexed_links") {
                                    $("#"+key).html(reportData[key]['count']);
                                    
                                    if (reportData[key]['msg_dynamic_urls']) {
                                        $("#dynamic_urls").html(reportData[key]['msg_dynamic_urls']);
                                        $("#dynamic_urls").attr('class', reportData[key]['msg_dynamic_urls_status']);
                                        $("#url-structure-box").show();
                                    } else {
                                        $("#dynamic_urls").remove();
                                    }
                                    
                                    if (reportData[key]['msg_url_length']) {
                                        $("#url_length").html(reportData[key]['msg_url_length']);
                                        $("#url_length").attr('class', reportData[key]['msg_url_length_status']);
                                        $("#url-structure-box").show();
                                    } else {
                                        $("#url_length").remove();
                                    }
                                } else if (key == 'sitemap_usage') {
                                    if (reportData[key]['msg']) {
                                        $("#sitemap_usage").html(reportData[key]['msg']);
                                        $("#sitemap_usage").attr('class', reportData[key]['msg_type']);
                                    } else {
                                        $("#sitemap_usage").remove();
                                    }
                                } else if (key == 'google_pagerank') {
                                    if (reportData[key]['msg']) {
                                        $("#google_rank").html(reportData[key]['msg']);
                                    } else {
                                        var rank = (reportData[key]) ? reportData[key] : 'n/a';
                                        $("#google_rank").html("<a href=\"http://www.google.com\" target=\"_blank\">Google</a> PageRank: "+rank);
                                    }
                                } else if (reportData[key]) {
                                    $("#"+key).html(reportData[key]);
                                }
                            }
                        }
                    }
                } else {
                     $("#"+groups[currentGroupIndex]+"-box-loader div[class='text']").text("An error occured");
                    // TODO display localized error
                }
                
                /*if (reportGroup==groups.length-2) {
                    document.body.style.cursor = 'auto';
                }*/
                
                if (groupComplete) {
                    $("#"+groups[currentGroupIndex]+"-box-loader").hide();
                    $("#"+groups[currentGroupIndex]+"-box").animate({
                        /*height: '100%',*/
                        opacity: 'show',
                        duration: 'normal'
                    }, 'slow');
                      initBulbs("#"+groups[currentGroupIndex]+"-box");
                    
                    // show rankings
                    if (groups[currentGroupIndex] == 'technical') {
                        if (data.data.ranking.technical) {
                            $("#technical-score span").text(data.data.ranking.technical+"%");
                            $("#technical-score").show();
                            
                            // activate subnavigation
                            techLoaded = true;
                            $("ul").removeClass("inactive").addClass("active");
                            
                            // update list overview
                            var techsections = new Array("metadata", "url", "technologies", "performance");
                            
                            jQuery.each(techsections, function() {
                                var listItemName = this;
                                
                                var errors = $("#"+listItemName+"-section li.error").length;
                                var itemClass = (errors > 0) ? "error-info" : "success-info";
                                
                                var msg;
                                if (errors == 0) {
                                    msg = (this == 'technologies') ? noErrorsLabel : noProblemsLabel;
                                } else if (errors == 1) {
                                    msg = (this == 'technologies') ? oneErrorLabel : oneProblemLabel;
                                } else if (errors > 1) {
                                    msg = (this == 'technologies') ? moreErrorsLabel.split("%%COUNT%%").join(errors) : moreProblemsLabel.split("%%COUNT%%").join(errors);
                                }
                                
                                $("#tech-list-item-"+listItemName+" div").addClass(itemClass);
                                $("#tech-list-item-"+listItemName+" div").text(msg);
                                
                                $("#tech-list-item-"+listItemName).click(function() {
                                    $("#li-"+listItemName).trigger("click");
                                    techClick = true;
                                });
                                
                            });
                        }
                        
                        $("ul.tech-section-list li").removeClass("wait");
                        
                        // last group => overall score
                        if (data.data.ranking.overall) {
                            $("#overall-score span").text(data.data.ranking.overall+"%");
                            $("#overall-score").show();
                        }
                    } else if (groups[currentGroupIndex] == 'social') {
                        if (data.data.ranking.social) {
                            $("#social-score span").text(data.data.ranking.social+"%");
                            $("#social-score").show();
                        }
                    } else if (groups[currentGroupIndex] == 'social') {
                        if (data.data.ranking.social) {
                            $("#social-score span").text(data.data.ranking.social+"%");
                            $("#social-score").show();
                        }
                    } else if (groups[currentGroupIndex] == 'inbound1') {
                        if (data.data.ranking.social) {
                            $("#searchengines-score span").text(data.data.ranking.searchengines+"%");
                            $("#searchengines-score").show();
                            
                            // activate subnavigation
                            searchenginesLoaded = true;
                            inboundLoaded = true;
                            
                            $("ul").removeClass("inactive").addClass("active");
                            
                            // update list overview
                            var searchenginessections = new Array("rankings", "indexed", "inbound");
                            
                            jQuery.each(searchenginessections, function() {
                                var listItemName = this;
                                
                                $("#searchengines-list-item-"+listItemName).click(function() {
                                    $("#li-"+listItemName).trigger("click");
                                    searchenginesClick = true;
                                });
                            });
                        }
                        $("#searchengines-list-item-inbound").removeClass("wait");
                        $("#searchengines-list-item-indexed").removeClass("wait");
                        $("#searchengines-list-item-rankings").removeClass("wait");
                        $("#chart-inbound").show();
                    } else if (groups[currentGroupIndex] == 'listings') {
                        $("#chart-indexed").show();
                        indexedLoaded = true;
                    } else if (groups[currentGroupIndex] == 'rank') {
                        rankLoaded = true;
                    }
                    
                    // keywords are always loaded so always show it
                    if (data.data && data.data.ranking && data.data.ranking.keywords) {
                        $("#keywords-score span").text(data.data.ranking.keywords+"%");
                        $("#keywords-score").show();
                    }
                }
                    
                //currentGroupIndex = currentGroupIndex;
                currentGroupItemsCount = data.data["groupItems"];
                currentItem = groupComplete ? data.data["groupItems"] : data.data["item"];
                
                queryReports(url);
            }
        );
    }
}

var section = "dashboard";
var techsection = null;
var searchenginessection = null;
var stopSwitch = false;

function initNav() {
    var sections = new Array(
        "dashboard", "home", "searchengines", "social", "tech", "keywords", "usability", "privacy", "buttons"
    );

    var techsections = new Array(
        "techoverview", "metadata", "url", "technologies", "performance"
    );

    var searchenginessections = new Array(
        "searchenginesoverview", "rankings", "indexed", "inbound"
    );
    
    var techClick = false;
    var searchenginesClick = false;
    
    // Main Navigation
    jQuery.each(sections, function() {
        $("#li-"+this+".main").click( function(e) {
            //console.log("main");
            if (!stopSwitch) {
                stopSwitch = true;
                e.preventDefault();
                
                var id = new String($("a", this).attr("href")).split("#")[1];
                $("a", this).blur();
                
                $("#"+section+"-section").fadeOut(75, function(point) {
                    $("#"+id+"-section").fadeIn(75);
                    stopSwitch = false;
                });
                
                //if (id!='tech' && section!='tech') {
                    $("#report-nav li.main").removeClass("active");
                //}
                //console.log("hide nav - "+$("#report-nav li[class='main']").length);
                $("#li-"+id).addClass("active");
                
                if (id=='tech') {
                    //console.log("techClick="+techClick);
                    if (!techClick) {
                        $("#techoverview-section").fadeIn(75);
                        jQuery.each(techsections, function() {
                            if (this!='techoverview') {
                                $("#"+this+"-section").hide();
                                $("#tech-nav li").removeClass("active");
                            }
                        });
                        $("#tech-nav").hide();
                    } else {
                        techClick = false;
                        
                    }
                } else {
                    $("#tech-nav").hide();
                    $("#tech-nav li").removeClass("active");
                    techsection = null;
                }
                
                if (id=='searchengines') {
                    if (!searchenginesClick) {
                        $("#searchenginesoverview-section").fadeIn(75);
                        jQuery.each(searchenginessections, function() {
                            if (this!='searchenginesoverview') {
                                $("#"+this+"-section").hide();
                                $("#searchengines-nav li").removeClass("active");
                            }
                        });
                        $("#searchengines-nav").hide();
                        //console.log("hide nav - click="+searchenginesClick);
                    } else {
                        searchenginesClick = false;
                    }
                } else {
                    $("#searchengines-nav").hide();
                    //console.log("hide nav id = "+id+" - else - click="+searchenginesClick);
                    $("#searchengines-nav li").removeClass("active");
                    searchenginessection = null;
                }
                
                //location.hash = id;  
                
                section = id;
            }
        });
        
    });
    
    // Tech Subnavigation
    jQuery.each(techsections, function() {
        $("#li-"+this+".sub").click( function(e) {;
            e.preventDefault();
            $("#tech-nav").show();
            
            if (techLoaded) {
                techClick = true;
                //console.log("tech - hide");
                $("#techoverview-section").hide();
                
                //console.log("tech");
                var id = new String($("a", this).attr("href")).split("#")[1];
                $("a", this).blur();
                
                $("#tech-nav li").removeClass("active");
                $("#li-"+id).addClass("active");
                
                if (techsection==null) {
                    techsection = 'techoverview';
                }
                
                //console.log("click "+id+" - hide "+techsection+" - show "+id+" - activate li-"+id+" - id ref="+$("#li-"+id));
                
                $("#"+techsection+"-section").fadeOut(75, function(point) {
                    $("#"+id+"-section").fadeIn(75);
                });
                
                /*
                if (id != "techoverview") {
                    $("#techoverview-section").hide();
                }
                */
                techsection = id;
                //location.hash = id;
            }
        });
        
    });
    
    // Searchengines Subnavigation
    jQuery.each(searchenginessections, function() {
        var searchSectionName = this;
        $("#li-"+this+".sub").click( function(e) {;
            e.preventDefault();
            $("#searchengines-nav").show();
            var id = new String($("a", this).attr("href")).split("#")[1];
            
            if (
                id == "rankings" && rankLoaded ||
                id == "inbound" && inboundLoaded ||
                id == "indexed" && indexedLoaded ||
                searchenginesLoaded
            ) {
                searchenginesClick = true;
                $("#searchenginesoverview-section").hide();
                
                //console.log("searchenginessection");
                id = new String($("a", this).attr("href")).split("#")[1];
                $("a", this).blur();
                
                $("#searchengines-nav li").removeClass("active");
                $("#li-"+id).addClass("active");
                
                if (searchenginessection==null) {
                    searchenginessection = 'searchengines';
                }
                
                //console.log("click "+id+" - hide "+searchenginessection+" - show "+id+" - activate li-"+id+" - id ref="+$("#li-"+id));
                
                $("#"+searchenginessection+"-section").fadeOut(75, function(point) {
                    $("#"+id+"-section").fadeIn(75);
                });
                
                /*
                if (id != "techoverview") {
                    $("#techoverview-section").hide();
                }
                */
                searchenginessection = id;
                //location.hash = id;
            }
        });
        
    }); 
    
    /*
    $("#report-nav li").each(
        function() {
            console.log("list elem - "+$(this));
            
            $(this).bind("click", function() {
                var src = $("a", this).attr("src");
                console.log($(this, "a"));
                //console.log("link: "+$(this, "a").attr("src"));
                //selectSection($("a", this).attr("src").split('#').join(''));
            });
        }
    );
    */
}

function initBulbs(box) {
	var selector = "";
	if (box) {
		selector = box+" ";
	}

    jQuery(document).ready( 
        function() {
            $(selector+"img[src$=lightbulb.png]").each(
		        function(intIndex) {
			        $( this ).hover(function(){
				        var src = $(this).attr('src');
				        $(this).attr('src', src.split('lightbulb.png').join('lightbulb_on.png'));
			        });
			        $( this ).mouseout(function(){
				        var src = $(this).attr('src');
				        $(this).attr('src', src.split('lightbulb_on.png').join('lightbulb.png'));
			        });
		        }
	        );
        }
    );
}

function initDetails() {
    $("a[class='details-expand']").each(
        function(i) {
            $(this).focus(function(i) {
                $(this).blur();
            });
            $(this).toggle(
                function(e) {
                    //console.log('expand - '+$(this));
                    
                    $(this).attr('class', '');
                    $(this).addClass('details-collpase');
                    $('span', $(this)).text(hideDetailsLabel);
                    $(this).next().slideToggle();
                    
                    //console.log($(":parent", this).next("span"));
                },
                function(e) {
                    //console.log('collapse - '+$(this));
                    
                    $(this).attr('class', '');
                    $(this).attr('class', 'details-expand');
                    $('span', $(this)).text(showDetailsLabel);
                    $(this).next().slideToggle();
                    
                    //console.log($(":parent", this).next("span"));
                }
            );
        }
    );
}

function setInboundLinksType(type) {
    $(".inbound-links-page").hide();
    if (type == 'domains') {
        $("#inbound-links-pager").pager({ pagenumber: 1, pagecount: inboundDomainsPagesCount, buttonClickCallback: InboundDomainsClick });
        if (inboundDomainsPagesCount < 2) {
            $("#inbound-links-pager").hide();
        } else {
            $("#inbound-links-pager").show();
        }
        $("#inbound-domains-page-1").show();
    } else {
        $("#inbound-links-pager").pager({ pagenumber: 1, pagecount: inboundLinksPagesCount, buttonClickCallback: InboundLinksClick });
        if (inboundLinksPagesCount < 2) {
            $("#inbound-links-pager").hide();
        } else {
            $("#inbound-links-pager").show();
        }
        $("#inbound-links-page-1").show();
    }
}

InboundDomainsClick = function(pageclickednumber) {
    $("#inbound-links-pager").pager({ pagenumber: pageclickednumber, pagecount: inboundDomainsPagesCount, buttonClickCallback: InboundDomainsClick });
    $(".inbound-links-page").hide();
    $("#inbound-domains-page-"+pageclickednumber).show();
}

InboundLinksClick = function(pageclickednumber) {
    $("#inbound-links-pager").pager({ pagenumber: pageclickednumber, pagecount: inboundLinksPagesCount, buttonClickCallback: InboundLinksClick });
    $(".inbound-links-page").hide();
    $("#inbound-links-page-"+pageclickednumber).show();
}
    
$(document).ready(function(){
    
    /*$("div[class='tagcloud'] span").tooltip({ 
        track: true, 
        delay: 0, 
        showURL: false, 
        opacity: 1, 
        fixPNG: true,
        bodyHandler: function() { 
            return $($(this).attr("title")); 
        }, 
        //showBody: " - ", 
        //extraClass: "pretty fancy", 
        top: -15, 
        left: 5 
    });*/
    
    initNav();
    initDetails();
    
    //$("#dashboard-section").imageZoom();
    
    /*$('body').supersleight();*/

    initBulbs();
    
    $(document).ready(function() {
        if (typeof(window["inboundLinksPagesCount"]) != "undefined") {
            $("#inbound-links-pager").pager({ pagenumber: 1, pagecount: inboundLinksPagesCount, buttonClickCallback: InboundLinksClick });
            if (inboundLinksPagesCount < 2) {
                $("#inbound-links-pager").hide();
            }
            
        }
    });
    
    queryReports(query);
    
});