/// <reference path="../jquery-1.4.1-vsdoc.js" />

$(document).ready(function () {

    ApplyHoverToArticleItem();



    //    $.each($("#topmenu ul a"), function () { if (window.location.href.indexOf($(this).attr("href")) != -1) { $(this).addClass("tSelected"); return false; }; });
    //    $("#langBox").hover(function () { $('#langDropMenu').show(); $(this).addClass("backWhite"); }, function () { $('#langDropMenu').hide(); $(this).removeClass("backWhite"); });

    //    $("#LoginBox").hover(function () { $('#LoginDropPan').show(); $(this).addClass("backWhite"); }, function () { $('#LoginDropPan').hide(); $(this).removeClass("backWhite"); });

    $("#BackGroundDiv").width($(window).width()).height($(window).height());

    try {
        $(".imgbox").imgbox({ 'speedIn': 0, 'speedOut': 0, 'alignment': 'center', 'overlayShow': true, 'allowMultiple': true });
    } catch (e) {

    }

    $(".liExploreLinks").hover(function () {
        SetExploreLinksDiv();
        $(".divExploreLinks").fadeIn();
    }, function () {
        $(".divExploreLinks").hide();
    });


    //Apply vc to all anchors
    if (getParameterByName("vc") != "") {
        $("a").each(function () {
            if ($(this).attr("href") != undefined && $(this).attr("href").toLowerCase().indexOf("/") > -1 && $(this).attr("href").toLowerCase().indexOf("vc=") == -1) {
                if ($(this).attr("href").indexOf("?") > -1) {
                    $(this).attr("href", $(this).attr("href") + "&vc=" + getParameterByName("vc"));
                } else {
                    $(this).attr("href", $(this).attr("href") + "?vc=" + getParameterByName("vc"));
                }
            }
        });
    }

    try {
        $(".datepicker").datepicker({
            changeMonth: true,
            changeYear: true,
            yearRange: '-100:+0'
        });
    } catch (e) { }

    //Search autocomplete
    var autoSelect = function (event, ui) {
        if (ui.item) {
            window.location.href = "/" + ui.item.TagDNS + (ui.item.ObjectType == 1 ? ("/" + ui.item.ItemDNS) : "");
        }
    };
    var autoRenderItem = function (ul, item) {
        return $("<li></li>")
				.data("item.autocomplete", item)
				.append("<a><table cellpadding='0' cellspacing='0' border='0'><tr><td valign='middle'><img style='width:45px' src='" + ((item.ImageName == ""|| item.ImageName == null) ? "/images2/NoImage1.jpg" : "/Home/Thumbnail?id=" + item.ImageName + "&width=45") + "' /></td><td valign='middle'><div style='padding:0 10px;'>" + item.SearchTitle + "</div></td></tr></table></a>")
				.appendTo(ul);
    };

    try {
        $("#inputSearch").autocomplete({
            source: "/Home/AutoCompleteResult?listType=3",
            minLength: 2,
            select: autoSelect
        }).data("autocomplete")._renderItem = autoRenderItem;

        $("#inputSearch2").autocomplete({
            source: "/Home/AutoCompleteResult?listType=3",
            minLength: 2,
            select: autoSelect,
            position: { my: "left bottom", at: "left top", collision: "none" }
        }).data("autocomplete")._renderItem = autoRenderItem;
    } catch (e) {

    }
    



});

function ApplyHoverToArticleItem() {
    $(".article-item").each(function () {
        if (!$(this).hasClass("nohover")) {
            $(this).hover(
              function () {
                  $(this).addClass("hover");
                  $(this).find('.yt-uix-btn_2').removeClass('yt-disable').addClass('yt-select');
              },
              function () {
                  $(this).removeClass("hover");
                  $(this).find('.yt-uix-btn_2').removeClass('yt-select').addClass('yt-disable');
              }
            );
        }
    });
}

  function getParameterByName(name) {
      name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
      var regexS = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(window.location.href);
      if (results == null)
          return "";
      else
          return decodeURIComponent(results[1].replace(/\+/g, " "));
  }



function CallASMXService(webMethod, parameters, callpack){

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (callpack != null) callpack(msg.d);
        },
        error: function (e) {
            alert(webMethod + "call error.");
        }
    });
}

jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

function SetExploreLinksDiv() {
    var divExploreLinks_width = $(".divExploreLinks").width();
    var liExploreLinks_width = $(".liExploreLinks").width();
    //var liExploreLinks_left = $(".liExploreLinks").offset().left;
    //var newleft = liExploreLinks_left - ((divExploreLinks_width - liExploreLinks_width) / 2);
    var newleft =  - ((divExploreLinks_width - liExploreLinks_width) / 2);
    $(".divExploreLinks").css("left", newleft);
}

function removeParameter(url, parameter) {
    var urlparts = url.split('?');

    if (urlparts.length >= 2) {
        var urlBase = urlparts.shift(); //get first part, and remove from array
        var queryString = urlparts.join("?"); //join it back up

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = queryString.split(/[&;]/g);
        for (var i = pars.length; i-- > 0; )               //reverse iteration as may be destructive
            if (pars[i].lastIndexOf(prefix, 0) !== -1)   //idiom for string.startsWith
                pars.splice(i, 1);

        if (pars.length > 0)
            url = urlBase + '?' + pars.join('&');
        else
            url = urlBase;
    }
    return url;
}

//#################################################################################################################################################################
// ## Authentication & User Creation ##
function CheckIfUserAuthenticated(f, p) {
    $.ajax({
        url: "/Handlers/AuthenticationHandler.ashx?f=IsAuthenticate",
        type: 'GET',
        async: false,
        cache: false,
        timeout: 30000,
        error: function () {
            f(p, false);
        },
        success: function (msg) {
            if (msg == "t") {
                if (p == undefined) f(true); else  f(p, true);
            } else {
                if (p == undefined) f(false); else f(p, false);
            }
        }
    });
}

function IsUserAuthenticated() {
    var result;
    $.ajax({
        url: "/Handlers/AuthenticationHandler.ashx?f=IsAuthenticate",
        type: 'GET',
        async: false,
        cache: false,
        timeout: 30000,
        error: function () { alert("IsUserAuthenticated error (in Main.js file)"); },
        success: function (msg) { result = msg; }
    });

    return result == "t";
}

function showLogin() {
    $("#LoginDropPan").center();
    $("#BackGroundDiv").show();
    $("#LoginDropPan").fadeIn();
    return false;
}

function MembersOnly(showUnderConstraction) {
    if (IsUserAuthenticated()) {
        if (showUnderConstraction != undefined && showUnderConstraction) {
            return ShowUndrConstraction();
        }
        return true;
    }
    //return showLogin();yamen
    return showRegisterForm();
}

function ShowUndrConstraction() {
    window.location.href = "/Home/UnderConstraction?ret=" + removeParameter(window.location.pathname, "msg").split("?")[0];
    return false;
}

function AuthenticateUser() {
    //if (!$("#LoginDropPan").validationEngine('validate')) return;
    
    var user = $("#tbxUserName").val();
    var pass = $("#tbxUserPass").val();
    var ok = true;

    if (user == "") {
        $("#UserNmaeRequered").show();
        ok= false;
    }
    if (pass == "") {
        $("#UserPassRequered").show();
        ok= false;
    }

    if (ok) {
        $.ajax({
            url: "/Handlers/AuthenticationHandler.ashx?f=AuthenticateUser&u=" + user + "&p=" + pass,
            type: 'GET',
            async: false,
            cache: false,
            timeout: 30000,
            error: function () {
                $("#AutheFailed").show();
                return false;
            },
            success: function (msg) {
                if (msg == "t") {
                    $("#AuthSuccess").show();
                    $("#UserNmaeRequered").hide();
                    $("#UserPassRequered").hide();
                    $("#AutheFailed").hide();
                    if (getParameterByName("ret") != "") {
                        window.location.href = getParameterByName("ret");
                    }
                    else {
                        //window.location.reload();
                        window.location.href = removeParameter(window.location.href, "msg"); //.reload();
                    }
                } else {
                    $("#AutheFailed").show();
                }
            }
        });
    }

    return false;
}
function AuthenticateUser2() {

}

function showRegisterForm() {
    $("#RegistrationPan").center();
    $("#BackGroundDiv").show();
    $("#RegistrationPan").fadeIn();
    return false;
}

function CreateUser() {
    if (!$("#RegistrationPan").validationEngine('validate')) return;

    if (!$("#cbxRegisterApprove").is(":checked")) {
        alert($("#cbxRegisterApprove").attr("title"));
        return false;
    }
    //show loading
    //--
    var localpath = window.location.pathname.split("?")[0];
    var vc = getParameterByName("vc");
    $.get("/Handlers/AuthenticationHandler.ashx?f=CreateUser&vc=" + vc + "&ret=" + localpath, $("input,select,password", "#RegistrationPan").serialize(),
        function (msg) {
            if (msg == "t") {
                $("#RegisterSuccess").show();
                $("#UserNmaeRequered2").hide();
                $("#UserPassRequered2").hide();
                $("#UserPassRequered2").hide();
                $("#RegisterFailed").hide();
                //window.location.reload();

                //window.location.href = "/Account/InviteFriends/" + $("#RegistrationPan input[name=Email]").val() + "?ret=" + localpath + "&vc=" + vc;
                window.location.href = "/Account/InviteFriends?ret=" + localpath + "&vc=" + vc;
            } else {
                $("#RegisterFailed").show();
                //return false;
            }

            return false;
        }
    );
    


        
    return false;
}


function LogOutUser() {
    $.get("/Handlers/AuthenticationHandler.ashx?f=LogOut",
        function (msg) {
            window.location.href = removeParameter(window.location.href, "msg"); //.reload();
        }
    );
}

function closepopup() {
    $(".popup1_back").hide();
    //$('.popup1_back').validationEngine('hideAll');
    $(".formError").remove();
    $("#BackGroundDiv").hide();
}

function swichPopup(target) {
    //make sure that the popups in the center
    $("#RegistrationPan").center();
    $("#LoginDropPan").center();

    //$('.popup1_back').validationEngine('hideAll');
    $(".formError").remove();

    //swicth popup
    $(".popup1_back").hide();
    if(target=="join")
        $("#RegistrationPan").fadeIn();
    else
        $("#LoginDropPan").fadeIn();
}

function ShowForgetPassword(sender) {
    $(".formError").remove();
    $(sender).parents(".popup1_content").hide();
    $(sender).parents(".popup1_content").next(".popup1_content").show();
}

function ReturnToLoginPan(sender, send) {
    if (send) {
        var m = $("input[name = mailToSendPass]").val();
        $.get("/Handlers/AuthenticationHandler.ashx?f=ForgetPassword&mail=" + m,
            function (msg) {
                if (msg == "t") {
                    $("#ForgetPassSuccess").show();
                    $("#ForgetPassFailed").hide();
                } else {
                    $("#ForgetPassFailed").show();
                    $("#ForgetPassSuccess").hide();
                }
                $(sender).parents(".popup1_content").hide();
                $(sender).parents(".popup1_content").prev(".popup1_content").show();
            }
        );
    }
    else {
        $("#ForgetPassFailed").hide();
        $("#ForgetPassSuccess").hide();
        $(sender).parents(".popup1_content").hide();
        $(sender).parents(".popup1_content").prev(".popup1_content").show();

    }
    return false;
}

//#################################################################################################################################################################
// ## Voting ##
function MiniVoteItem(sender, num, itemid, tagid, appid, IsAuthenticated) { MiniVoteItem_Auth({sender:sender, num:num, itemid:itemid, tagid:tagid, appid:appid}); }
function MiniVoteItem_Auth(params, IsAuthenticated) {
    if(IsAuthenticated == undefined)
    {
        CheckIfUserAuthenticated(MiniVoteItem_Auth, params);
        return;
    }
    if (IsAuthenticated == false) {
        showLogin();
        return;
    }
    
    var sender=params.sender;
    var num=params.num;
    var itemid=params.itemid;
    var tagid=params.tagid;
    var appid=params.appid;

    var articleitem = $(sender).parents(".article-item");
    var oldplace = $(".itemplace", articleitem).text();

    //Show ajax loading
    $(".miniitem_voted", articleitem).hide();
    $(".miniitem_buttons", articleitem).hide();
    $(".miniitem_ajaxpnl", articleitem).show();

    //Determin wich arrow to show near the "Voted!"
    if ($(sender).hasClass("f_increase")) {
        $(".miniitem_votingchoice", articleitem).removeClass("s_deacrase_ic");
        $(".miniitem_votingchoice", articleitem).addClass("s_increase_ic");
    }
    else {
        $(".miniitem_votingchoice", articleitem).removeClass("s_increase_ic");
        $(".miniitem_votingchoice", articleitem).addClass("s_deacrase_ic");
    }

    
    $.get("/Handlers/VotingHandler.ashx", { num: num, url: '<%=Request.Url.ToString() %>', itemid: itemid, tagid: tagid, appid: appid },
        function (result) {
            

            for (var i = 0; i < result.length; i++) {
                var targitAI = $(".article-item[itemid=" + result[i].ItemID + "]");
                if (targitAI.length > 0) {
                    var targitplace = $(".itemplace", targitAI).text();
                    if ((targitplace * 1) != (result[i].NewTagPlace * 1)) {
                        $(".itemplace", targitAI).text(result[i].NewTagPlace);

                        //Set the row wich detrmine the new place (up or down)
                        $(".miniitem_newplacechoise", targitAI).show();
                        if((targitplace * 1) > (result[i].NewTagPlace * 1))
                        {
                            $(".miniitem_newplacechoise", targitAI).addClass("bts_increase_ic");
                        }
                        else{
                            $(".miniitem_newplacechoise", targitAI).addClass("bts_deacrase_ic");
                        }
                        
                        
                        if ((result[i].NewTagPlace * 1) == 1) {
                            //show cup
                            $(".miniitem_place", targitAI).hide();
                            $(".miniitem_cup", targitAI).show();
                        }
                        else {
                            //hide cup
                            $(".miniitem_place", targitAI).show();
                            $(".miniitem_cup", targitAI).hide();
                        }
                    }
                }
                
            }



            //Hide ajax loading
            $(".miniitem_voted", articleitem).show();
            $(".miniitem_ajaxpnl", articleitem).hide();

        }
    );

    }


    //### Search ###############################################################################################################################################
    function trim(stringToTrim) {
        return stringToTrim.replace(/^\s+|\s+$/g, "");
    }
    function ltrim(stringToTrim) {
        return stringToTrim.replace(/^\s+/, "");
    }
    function rtrim(stringToTrim) {
        return stringToTrim.replace(/\s+$/, "");
    }


    //### CloseSite ###############################################################################################################################################
    function CheckVisaCode() {
        if (IsUserAuthenticated()) return true;

        var vc = getParameterByName("vc");
        var itemId = getParameterByName("itemId");
        if (vc != "") {
            //return true;
            var result;
            $.ajax({
                url: "/Handlers/InviteHandler.ashx?f=CheckVisaCode&vc=" + vc + "&itemId=" + itemId,
                type: 'GET',
                async: false,
                cache: false,
                timeout: 30000,
                error: function (a, b, c, d) { alert("CheckVisaCode error (in Main.js file)"); },
                success: function (msg) { result = msg; }
            });

            return result == "t";
        }
        else {
            //setTimeout("$('body').addClass('borderclosed')", 2000);

            return false; //true ;
        }
    }

    //### AddItem ###############################################################################################################################################
    function CheckIfCanAddItem() {
        if (IsUserAuthenticated()) return true;
        showLogin();
        return false;
    }

    function OpenCompetitionRow(sender) {
        $(sender).next(".divBodyRow").slideToggle();
    }


    function InviteFriend_click(item) {
        var localpath = window.location.pathname.split("?")[0];
        var vc = getParameterByName("vc");
        if (item == 0) {
            //to site
            window.location.href = "/Account/InviteFriends?ret=" + localpath; //  + "&vc=" + vc;
        }
        else {


        }
    }

    //##############################################################################################################################

    function InviteSingleFriend_click(inviteType, _tid, _iid) {
        if ($("#tbxInviteMail").val().trim(" ") == "") return;

        if (!CheckIfCanAddItem()) return;


        var mail = $("#tbxInviteMail").val();
        var ret = window.location.pathname.split("?")[0];
        var tid = 0;
        var iid = 0;
        //var inviteType = "General";
        if (inviteType == "Item") {
            tid = _tid;
            iid = _iid;
        }
        var msg = "is";

        $.post("/Handlers/InviteHandler.ashx?f=InviteSingle&ret=" + ret + "&tid=" + tid + "&iid=" + iid + "&inviteType=" + inviteType + "&mail=" + mail, 
            function (data) {
                if (ret != "") {
                    window.location.href = ret + "?msg=" + msg; //InvitationSucceeded
                }
                else {

                    window.location.href = "/?msg=" + msg;
                }
            }
        );
    }

    function AuthenticatedByFacebook() {
        //if in private page
        if (window.location.href.indexOf("/Private") > -1) {
            var ret = getParameterByName("ret");
            if (ret == "" || ret == "/") window.location.href = "/";
            else window.location.href = ret;
            return;
        }

        //else restart current page
        window.location.href = removeParameter(window.location.href, "msg");
    }
