$(function(){
    // Replace plain character text input with password field on focus
    $('#password-clear').show();
    $('#password-password').hide();
    $('#password-clear').focus(function() {
        $(this).hide();
        $('#password-password').show().focus();
    });
    $('#password-password').blur(function() {
        if($(this).val() == '') {
            $('#password-clear').show();
            $(this).hide();
        }
    });
    // auto remove content in input fields on focus
    $("#article_search input").focus(function(){
        if(!kyani.focus_username){
            $(this).val("");
            kyani.focus_username = true;
        }
    });
    // toggle sub menus in sub navigation; left panel
    $(".section .menu").bind("click", function(){
        $(this).siblings().toggle();
        if(this.className != "info menu open"){
            $(this).addClass("open");
        }else{
            $(this).removeClass("open");
        }
    });
    // add navigation graphic to sub navigation; left panel
    $(".section a").bind("click", function(){
        $(".section a").removeClass("here");
        $(this).addClass("here");
    });
    // display language choice change
    $("#language-choice span").bind("click", function(){
        window.location = location.pathname + '?language='+ $(this).html();
    });
    // replace button text and submit form when button clicked
    $("#article_search button").bind("click", function(){
        kyani.login_fx();
        $("#article_form").submit();
    });
    // "enter" key in login inputs submits form
    $("#login-form input").keydown(function(event){
        if(event.keyCode == 13){
            kyani.login_fx();
            $("#login-form").submit();
        }
    });
    // iframe resize for framed content
    kyani.resize_frame();
    // binding "resize" in the window object breaks IE
    if ( !$.browser.msie ) {
        $(window).bind("resize", function(){
            kyani.resize_frame(); return true;
        });
    }
    // event information toggle; event section; office
    $(".event .head").bind("click", function(){
        $(this).siblings().toggle();
    });
    // table stripes; download section
    $("table.download-data tr:even td").addClass("alt");
    // download category choice control
    $("#col2 select").bind("change", function(){
        $(this).parent().submit();
    });
    // flash player dynamic load; KSA, articles
    kyani.load.flowplayer();
    // init dashboard; office
    if($("div.dashboard").length > 0){
        if($.browser.msie){
            $(".vert").addClass("vert-ie").removeClass("vert");
            $(".vert-rep").addClass("vert-rep-ie").removeClass("vert-rep");
        }
        //$.ajax(kyani.dash.params("personal",false));
        //$.ajax(kyani.dash.params("events",false));
        $.ajax(kyani.dash.params("volume",true));
        $.ajax(kyani.dash.params("recruit",true));
        //$.ajax(kyani.dash.params("promotions",true));
        $.ajax(kyani.dash.params("orders",true));
        $.ajax(kyani.dash.params("customers",true));
        $.ajax(kyani.dash.params("rank",false));
    }
    // rounded corners on promo images on public
    if(!$.browser.msie){
        $("div.promo").each(function(){
            img = $("img", this).get();
            $(img).load(function(){
                h = $(this).height(); w = $(this).width();
                sc = "url("+$(this).attr("src")+")";
                if(h > 0 && w > 0){
                    $(this).parent().css({height:h,width:w,"background-image":sc});
                    $(this).remove();
                }
            });
        });
    }
    // change css for Asian languages
    if(kyani.lonograph == true){
        $("body").addClass("lonograph");
    }
    // random header banners
    // kyani.banner.process();
});
kyani = {
    processing_text: "PROCESSING ...",
    lonograph: false,
    focus_username: false
};
kyani.resize_frame = function(){
    if ( $("#iframe-holder").length != 1 ) {
        return false;
    }
    $("#iframe-holder").height("auto"); // reset height
    w = $(window).height();
    d = $(document).height();
    if(w >= d){
        v = w-220;
    }else{
        v = d-220;
    }
    $("#iframe-holder").height(v+"px");
    return true;
};
kyani.safari_message = function(){
    if((/Safari/.test(navigator.userAgent)) && !(/Chrome/.test(navigator.userAgent))){
        html = "<div class='safari_message'>";
        html += "Currently we cannot fully support the Safari web browser. Legacy pages are not correctly showing session information. We are working with our vendors to correct the problem. <a href='http://firefox.com' target='_blank'>Firefox</a> is a free download and is fully supported.";
        html += "</div>";
        
        $("body").prepend(html);
        return true;
    }
    return false;
};
kyani.login_fx = function(){
    $("#article_search button").text(kyani.processing_text);
};
kyani.load = {};
kyani.load.ksa = function(title){
    $("#content_space").animate({opacity:"0.5"});
    $("body").append(kyani.load.loading_img);
    var o = {
        dataType: "html",
        url: "ajax/ksa.get_article.php",
        data: {ksa:title},
        success: function(r){
            $("#content_space").html(r);
            kyani.load.flowplayer();
        },
        error: function(){
            alert("Error pulling page info. Please contact support.");
        },
        complete: function(){
            $("#content_space").animate({opacity:"1"});
            $("#loading").remove();
        }
    };
    $.ajax(o);
};
kyani.load.flowplayer_status = false;
kyani.load.loading_img = '<div id="loading"><img src="/assets/images/ajax-loader.gif"/></div>';
kyani.load.flowplayer = function(){
    if($("a.vidblock").length == 0){
        return false;
    }
    // load flowplayer js if not already loaded
    if(!this.flowplayer_status){
        $.ajaxSetup({async: false});
        $.getScript('/assets/js/flowplayer/flowplayer-3.1.4.min.js');
        $.ajaxSetup({async: true});
        this.flowplayer_status = true;
    }
    //Flash Streaming Skin
    $f("a.vidblock","/assets/js/flowplayer/flowplayer-3.1.5.swf",{
        clip:{autoPlay:false}
    });
};
kyani.dash = {};
kyani.dash.params = function(location, table){
    var selector = "."+location+" .bd";
    if(table){ selector += " tbody"}
    var dashboard_date = $("#dashboard_date").val();
    return {
        data: {date:dashboard_date},
        success: function(r){
            kyani.dash.process(location, r, selector);
        },
        error: function(xml){
            var mes = kyani.dash.templates.error("http error");
            $(selector+" img").after(mes);
            $(selector+" img").remove();
        },
        dataType: "json",
        url: "ajax/dash_"+location+".php",
        type: "POST"
    };
};
kyani.dash.process = function(loc, r, sel){
    if(r.status != "success"){
        var mes = this.templates.error(r.description);
        $(sel).html(mes);
        return false;
    }
    var data = this.templates.fill(loc, r);
    if(data){
        $(sel).html(data);
    }
};
kyani.dash.templates = {};
kyani.dash.templates.fill = function(loc, o){
    switch(loc){
        case "customers":
            html = this.customers(o.data);
            break;
        case "orders":
            html = this.orders(o.data);
            break;
        case "promotions":
            html = this.promotions(o.data);
            break;
        case "recruit":
            html = this.recruit(o.data);
            break;
        case "volume":
            html = this.volume(o.data);
            break;
        case "events":
            html = this.events(o.data);
            break;
        case "personal":
            html = this.personal(o);
            break;
        case "rank":
            html = this.rank(o);
            break;
        default:
            html = "Did not recognize: "+loc;
    }
    return html;
};
kyani.dash.templates.error = function(desc){
    return "<span class='error'>"+desc+"</span>";
};
kyani.dash.templates.customers = function(o){
    var html = ""; var pv = 0; var cv = 0;
    for(i=0;i<o.length;i++){
        html += "<tr>\n";
        //html += "<td><a href='javascript: alert(\""+ o[i].id +"\")'>";
        //html += o[i].name +"</a></td>\n";
        html += "<td>"+ o[i].id + " " + o[i].name +"</td>\n";
        html += "<td>"+ o[i].type +"</td>\n";
        html += "<td class='numbers'>"+ kyani.formatNum(o[i].pv) +"</td>\n";
        html += "<td class='numbers'>"+ kyani.formatNum(o[i].cv) +"</td>\n";
        html += "</tr>\n";
        pv += Number(o[i].pv);
        cv += Number(o[i].cv);
    }
    html += "<tr>";
    html += "<td style='border-top:1px solid #ccc'>"+o.length+"</td>";
    html += "<td></td>";
    html += "<td style='border-top:1px solid #ccc'>"+kyani.formatNum(pv)+"</td>";
    html += "<td style='border-top:1px solid #ccc'>"+kyani.formatNum(cv)+"</td>";
    html += "</tr>";
    
    return html;
};
kyani.dash.templates.orders = function(o){
    var html = "";
    for(i=0;i<o.length;i++){
        html += "<tr>\n";
        //html += "<td><a href='javascript: alert(\""+ o[i].id +"\")'>"+ o[i].id +"</a></td>\n";
        html += "<td>"+ o[i].id +"</td>\n";
        html += "<td>"+ o[i].status +"</td>\n";
        html += "<td class='numbers'>"+ kyani.formatNum(o[i].volumes) +"</td>\n";
        html += "<td>"+ o[i].date +"</td>\n";
        html += "</tr>\n";
    }
    return html;
};
kyani.dash.templates.promotions = function(o){
    var html = "";
    for(i=0;i<o.length;i++){
        html += "<tr>\n";
        html += "<td>"+ o[i].name +" ("+ o[i].id +")</td>\n";
        html += "<td>"+ o[i].from +"</td>\n";
        html += "<td>"+ o[i].to +"</td>\n";
        html += "<td>"+ o[i].date +"</td>\n";
        html += "</tr>\n";
    }
    return html;
};
kyani.dash.templates.recruit = function(o){
    var html = "";
    for(i=0;i<o.length;i++){
        html += "<tr>\n";
        html += "<td>"+ o[i].name +" ("+ o[i].id +")</td>\n";
        //html += "<td><a href='javascript: alert(\""+ o[i].id +"\")'>"+ o[i].recruits +"</a></td>\n";
        html += "<td class='numbers'>"+ o[i].recruits +"</td>\n";
        html += "</tr>\n";
    }
    return html;
};
kyani.dash.templates.volume = function(o){
    var html = "";
    for(i=0;i<o.length;i++){
        html += "<tr>\n";
        html += "<td>"+ o[i].name +" ("+ o[i].id +")</td>\n";
        //html += "<td><a href='javascript: alert(\""+ o[i].id +"\")'>"+ o[i].gv +"</a></td>\n";
        html += "<td class='numbers'>"+ kyani.formatNum(o[i].gv) +"</td>\n";
        html += "</tr>\n";
    }
    return html;
};
kyani.dash.templates.events = function(o){
    var html = "<ul>\n";
    for(i=0;i<o.length;i++){
        html += "<li>"+ o[i].date +": "+ o[i].description +" ("+ o[i].name +")</li>\n";
    }
    return html;
};
kyani.dash.templates.personal = function(o){
    var html = "\n<ul>\n";
    html += "<li>Paid as Rank: "+ o.rank +"</li>\n";
    html += "<li>Paid as Rank Expiration: "+ o.expire +"</li>\n";
    html += "<li>Personal Volume: "+ kyani.formatNum(o.pv) +"</li>\n";
    html += "<li>Autoship Status: "+ o.as_status +"</li>\n";
    html += "</ul>\n";
    return html;
};
kyani.dash.templates.rank = function(o){
    if(!o.status || o.status != "success"){
        return false;
    }
    
    $(".goal-amount").html(kyani.formatNum(o.goal));
    kyani.dash.rank.goal = o.goal;
    
    $(".current_rank").html(o.current_rank);
    $(".next_rank").html(o.next_rank);
    
    $("#rank-tracker-pvq").html(kyani.formatNum(o.volume.PV));
    
    total = 0;
    other_legs_total = 0;
    
    // build power leg
    kyani.dash.rank.build.power_leg(o.frontline[0]);
    
    // build 2nd leg
    kyani.dash.rank.build.second_leg(o.frontline[1], o.percentages);
    
    // build totals
    for(i=0;i<o.frontline.length;i++){
        if(i>1){
            other_legs_total += Number(o.frontline[i].contribution);
        }
        total = total + Number(o.frontline[i].contribution);
    }
    
    // build other legs
    kyani.dash.rank.build.other_legs(other_legs_total);
    
    total = Number(o.volume.PV) ? total + Number(o.volume.PV) : total;
    
    if(Number(o.volume.PV) < 100){
        //total = 0;
        $("#rank-tracker-personal").css("background-color","yellow");
        //$(".contr").css("text-decoration","line-through");
    }
    
    kyani.dash.rank.build.total(total);
    $(".rep-contr-amount").html(kyani.formatNum(total));
    return false; // force calling function to not replace the html
};
kyani.dash.rank = {
    goal: 0
};
kyani.dash.rank.build = {
    power_leg: function(rep){
        if(!rep){
            $("#rank-tracker-power-leg").parent().remove();
            return false;
        }
        if(kyani.dash.rank.goal == 300){
            cap_amount = 200;
        }else{
            cap = 60;
            cap_amount = (cap/100)*Number(kyani.dash.rank.goal);
        }
        fill_percent = (rep.contribution/cap_amount);
        // IE requires actual pixels. Will not work with % for height.
        box_h = $("#rank-tracker-power-leg").parent().parent().height();
        calc_h = Number(box_h) * fill_percent;
        percent_txt = calc_h.toString() + 'px';
        
        $("#rank-tracker-power-leg").parent().css({height: percent_txt});
        $("#LL-name").html(rep.name);
        $(".LL-contr-amount").html(kyani.formatNum(rep.contribution));
    },
    second_leg: function(rep, percentages){
        if(!rep){
            $("#rank-tracker-second-leg").parent().parent().remove();
            return false;
        }
        min_percent = 47.5;
        power_percent = Number(percentages[0]) ? Number(percentages[0]) : 0;
        if(power_percent > min_percent){
            cap = min_percent - (power_percent - min_percent);
        }else{
            cap = min_percent;
        }
        cap_amount = (cap/100)*Number(kyani.dash.rank.goal);
        fill_percent = (rep.contribution/cap_amount);
        box_h = $("#rank-tracker-second-leg").parent().parent().height();
        calc_h = Number(box_h) * fill_percent;
        percent_txt = calc_h.toString() + 'px';
        
        $("#rank-tracker-second-leg").parent().css({height: percent_txt});
        $("#2L-name").html(rep.name);
        $(".2L-contr-amount").html(kyani.formatNum(rep.contribution));
    },
    other_legs: function(total){
        if(total == 0){
            $("#rank-tracker-other-leg").parent().parent().remove();
            return false;
        }
        percent = total/Number(kyani.dash.rank.goal);
        box_h = $("#rank-tracker-other-leg").parent().parent().height();
        calc_h = Number(box_h) * percent;
        percent_txt = calc_h.toString() + 'px';
        
        $("#rank-tracker-other-leg").parent().css({height: percent_txt});
        $(".other-contr-amount").html(kyani.formatNum(total));
    },
    total: function(total){
        percent = total/kyani.dash.rank.goal;
        box_h = $("#current").parent().parent().height();
        calc_h = Number(box_h) * percent;
        percent_txt = calc_h.toString() + 'px';
        $("#current").parent().css({height: percent_txt});
    }
}
kyani.banners = {
    location: "/assets/images/banners/",
    images: [
        "BearOnLog",
        "BearOnTheFalls",
        "BlueMountain",
        "BlueberriesWithLeaves",
        "Blueberries",
        "BlueberryBranch",
        "Forest",
        "GreenMountains",
        "MountainSunset",
        "Mountainscape",
        "WildBlueberries"
    ]
};
kyani.banners.process = function(){
    if($("#header").height() > 110){
        banner = kyani.banners.get("Wide");
    }else{
        banner = kyani.banners.get("Skinny");
    }
    $("#header").css("background-image","url("+banner+")");
}
kyani.banners.get = function(type){
    image = this.images[Math.floor(Math.random()*this.images.length)];
    return this.location + image + "_" + type + ".png";
};
kyani.addCommas = function(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while(rgx.test(x1)){
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
};
kyani.formatNum = function(num){
    result = !Number(num) ? 0 : Number(num);
    result = result.toFixed(0);
    return this.addCommas(result);
};
