﻿/// <reference path="jquery.js" /> 
/// <reference path="json2.js" />
/// <reference path="frame.js" />
/// <reference path="flot/jquery.flot.js" />


function Login(emailID, passwordID, buttonID)
{
    var email;
    var password;
    
    function InitEmail()
    { 
        $(emailID).focus().blur(function() {
            email = $(this).val();
            json("model.asmx/CheckEmail", {email:email}, false, function(d) {
                if (d.d) {
                    $(emailID).css({border : "0px;"});
                }
            });
        });
    }
    
    function InitPassword() 
    {
        $(passwordID).keyup(function(e) { 
           if(e.keyCode == 13) {
                $(buttonID).click();
           }
       }); 
    }
    
    function InitButton()
    {
        $(buttonID).click(function() {
            password = $(passwordID).val();
            $(buttonID).attr('disabled','disabled').unbind('click');
            json("model.asmx/LoginAttempt", {email : email, password : password}, false, function(d) {
                $(buttonID).removeAttr('disabled');
                InitButton();
                if (d.d.success) { 
                    Master();
                }
                else
                {
                    $("#loginMsg").text(d.d.msg);
                }
            });
        });
    } 
    
    function Init()
    {  
        $("#login").show().siblings().hide();
        InitEmail(); 
        InitPassword();
        InitButton();
    }
    
    Init();
}

function Master()
{ 
    $("#Master").show().siblings().hide();
    $("#logout").show();
   
   
   jQuery.fn.mouseOverClass = function(hover)
   {
     this.mouseover(function() {
            $(this).removeClass(hover).addClass(hover);
        }).mouseout(function() {
            $(this).removeClass(hover);
        });
   }
    
    //get urls
    json("model.asmx/AllUrls", {}, true, function(msg) {
        $("#allUrlsTable tr").remove();
        for (var i =0; i < msg.d.length; i++)
        {
            $("#allUrlsTable").append(msg.d[i]);
        }  
        
        
        
        
        $("#allUrlsTable tr").find("td:eq(2)").addClass("shortURL") 
        .mouseover(function() {
            $(this).parent().removeClass("hover").addClass("hover");
        }).mouseout(function() {
            $(this).parent().removeClass("hover");
        }).click(function() {
                var selected = $(this).parent().find("input").attr('name');
                $("#allUrlsTable td input").removeAttr("checked"); 
                $(this).parent().find("input").attr('checked', 'checked').click().attr('checked', 'checked');
                
            }); 
            
        $("#TableBox table").tablesorter();    
    }); 
   

    $("#orderBySelect").change(function() {
        $("#TableBox table th:eq("+$(this).val()+")").click();
    });
    
    
    $("#Delete").click(function() {
        var data = [];
     
         $("#allUrlsTable input:checked").each(function () {
            var key = $(this).attr("name");
            data.push(key);   
        });
        
        json("model.asmx/Delete", {names : data.join(",")}, true, function(msg) {  $("#allUrlsTable input:checked").parent().parent().fadeOut(function() {$(this).remove();}); });
        return false;
    });
    
    
   function tabs(div)
   {
        $(div + " .tabs .tab").click(function() {
            var tab = $(this).attr("id").replace("tab-", ""); 
            $("#tab-" + tab + ", #page-" + tab).addClass("selected").siblings().removeClass("selected");
        }).mouseOverClass("hover");
        
   }
   
    function updateTabs()
    {
        //get tabs
        var data = [];
     
         $("#allUrlsTable input:checked").each(function () {
            var key = $(this).attr("name");
            data.push(key);   
        });
        
        //show loading in tabs
            
       json("model.asmx/Tabs", {names : data.join(",") }, true, function(msg) { 
              $("#infoLongURL").text(msg.d.infoLongURL);
              $("#infoNotifyURL").text(msg.d.infoNotifyURL);
              $("#infoCreateDate").text(msg.d.infoCreateDate);
              $("#infoNotifyDate").text(msg.d.infoNotifyDate);
              $("#infoIsPrivate").text(msg.d.infoIsPrivate);
              $("#infoTotalHits").text(msg.d.infoTotalHits);
              
              $("#page-refferer tbody").html(msg.d.tableReffer.join('\n') );
              $("#page-ip tbody").html(msg.d.tableIP.join('\n'));
              $("#page-Browser tbody").html(msg.d.tableBrowser.join('\n')); 
              
              $(".tabPage tbody tr:odd td").addClass('odd');
              
              if (data.length == 1)
                $("#tab-NotifyInfo").show();
              
        });
    }
   
   function HandlePlot (datasets)
    {
    
        function weekendAreas(axes) {
            var markings = [];
            var d = new Date(axes.xaxis.min);
            // go to the first Saturday
            d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
            d.setUTCSeconds(0);
            d.setUTCMinutes(0);
            d.setUTCHours(0);
            var i = d.getTime();
            do {
                // when we don't set yaxis the rectangle automatically
                // extends to infinity upwards and downwards
                markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
                i += 7 * 24 * 60 * 60 * 1000;
            } while (i < axes.xaxis.max);
     
            return markings;
        }
        
        var options = {
            lines: { show: true },
            xaxis: { mode: "time" },
            yaxis: { tickDecimals: 0 },
            selection: { mode: "xy" },
            //points: { show: true },
            //bars: { show: true },
            grid: { markings: weekendAreas }
        };
        
        var plot;  
    
        // hard-code color indices to prevent them from shifting as
        // urls are turned on/off
        var i = 0;
        $.each(datasets, function(key, val) {
            val.color = i;
            ++i;
        });
        
        // insert checkboxes 
        var choiceContainer = $("#allUrlsTable"); 
        choiceContainer.find("input").click(plotAccordingToChoices);
     
        
        function plotAccordingToChoices() {
            updateTabs()
            var data = [];
     
            choiceContainer.find("input:checked").each(function () {
                var key = $(this).attr("name");
                $.each(datasets, function(k, val) {
                    if (val.label == key)
                    {
                        data.push(val);
                    }
                });  
            });
     
            if (data.length > 0)
            plot = $.plot($("#allUrlsChart"), data, options); 
            
            var overview = $.plot($("#overview"), data, {
                lines: { show: true, lineWidth: 1 },
                shadowSize: 0,
                xaxis: { mode: "time" },
                yaxis: { tickDecimals: 0 },
                legend: { show: false },
                selection: { mode: "xy" }
            });
         
            // now connect the two
            
            $("#allUrlsChart").bind("plotselected", function (event, ranges) {
                // do the zooming
                plot = $.plot($("#allUrlsChart"), data,
                              $.extend(true, {}, options, {
                                  xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                                  yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                              }));
         
                // don't fire event on the overview to prevent eternal loop
                overview.setSelection(ranges, true);
            });
            
            $("#overview").bind("plotselected", function (event, ranges) {
                plot.setSelection(ranges);
            });
            
              
        }
     
        plotAccordingToChoices();
        
        $("#selectNone").click(function() {
            $("#allUrlsTable input:checked").removeAttr("checked");
            plotAccordingToChoices();
            return false;
        });
        $("#selectAll").click(function() {
            $("#allUrlsTable input").attr("checked", "checked");
            plotAccordingToChoices();
            return false;
        });
    }
    
    

    
   
   //get data
   function BasicChart() {
   json("model.asmx/BasicChart", {period : $("#samplePeriod option:selected").val() }, true, function(msg) { 
          if (msg.d.length > 0) {
                HandlePlot(msg.d); 
            }
    });
    };
     BasicChart();
    
    $("#samplePeriod").change(function() {
         BasicChart();
   });
    
    
    
    tabs("#topRight");
    
    $("#topRight").css({width : ($("#topHalf").width() - 372 ) + "px"});
     
   
}


$().ready(function() {
   json("model.asmx/FirstLoad", {}, false, function(msg) { 
    if(!msg.d) {Login("#email", "#password", "#btnLogin");}
    else {Master();}
   }); 
   
   $("#logout a").click(function() {
        json("model.asmx/Logout", {}, true, function(msg) { Login("#email", "#password", "#btnLogin"); });
        return false;
    });
    
    
    
});
