﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="forms.js" /> 

//http://malsup.com/jquery/form/#api
//http://docs.jquery.com/Plugins/Validation/validate#options
var timeOut;
var CurrentCategoryGuid;
$(document).ready(function () {
    $('#HeaderContainer h1').click(function () {
        window.location = "/default.aspx";
    });
    $('#CategoryMenuLinks').after("<div id='CategoryMenuBarBottom'></div>");
    $('.button').prepend("<div class='buttonend'></div>");
    $('.buttonSm').prepend("<div class='buttonend'></div>");
    //$('.newBook').prepend("<span id='newBookIcon'></span>");
    $('.buttonDisabled').prepend("<div class='buttonend'></div>");
    $('#txtSearch').keyup(function (e) {
        $('#hidden_BookId').val("");
        OnEnter(e, ".buttonSm");
    });
    SetSearchBarValues();
    SetAutoCompleteForSearchBar();
    SetCategriesMenuOnClick();
    $('#link_SignOut').click(function () {
        Master_SignOut(false);
    });
    $('#SearchMenuLink').click(function () {
        if ($("#SearchDropDown").is(':hidden')) {
            $("#SearchDropDown").slideDown("fast");
            $("#txtSearch").val("");
        }
        else
            $("#SearchDropDown").slideUp("fast");

    });
    $('#btn_CloseSearch').click(function () {
        $("#SearchDropDown").slideUp("fast");
    });

    $('#close').click(function () {
        $('#Master_LoginPwd, #Master_SignUpMail, #Master_LoginEMail').val("");
    });

//    $(".WhitePaperListing").hover(function () {
//        $(".WP_Logo_Img").vAlign();
//    });


});

function SetAutoCompleteForSearchBar() {
    $("#txtSearch").autocomplete(urlPrefix + "handlers/AutocompleteBooksData.ashx",
                    { extraParams: {
                        c: function() { return $('#label_SearchBar select').val(); },
                        t: function() { return $('input[name=rdoSearchType]:checked').val(); }
                    },
                        width: "430px",
                        cacheLength: 0,
                        formatItem: formatItem,
                        formatResult: formatResult,
                        selectFirst: false
                    }).result(function(event, data, formatted) {
                        var array = formatted.toString().split("^");
                        $('#hidden_BookId').val(array[1]);
                    }).bind("keydown", SelectCurrent_Autocomplete);
                    
                    
}
function SelectCurrent_Autocomplete(event) {
    var KEY = {
        UP: 38,
        DOWN: 40,
        PAGEUP: 33,
        PAGEDOWN: 34
    };
    switch (event.keyCode) {
        case KEY.UP:
        case KEY.DOWN:
        case KEY.PAGEUP:
        case KEY.PAGEDOWN:
            //event.preventDefault();
            $("#txtSearch").attr("value", $(".ac_over").text());
            break;
    }
}

function formatItem(row) {
    var array = row.toString().split("^");
    var item = array[0];
    if (item.length > 65)
        item = item.substring(0, 65) + "...";
    return item;

}
function formatResult(row) {
    var array = row.toString().split("^");
        var item = array[0];
    if (item.length > 65)
        item = item.substring(0, 65);
    return item;
}

function GoSearch() {
    if ($("#hidden_BookId").val() != "") {
        $.goTo(urlPrefix + "BookDetail.aspx?id=" + $("#hidden_BookId").val());
    }
    else {
        $.goTo(urlPrefix + "Browse.aspx?cid=" + $("#label_SearchBar select").val()
                          + "&type=" + $.URLEncode($('input[name=rdoSearchType]:checked').val())
                          + "&text=" + $.URLEncode($('#txtSearch').val()));
    }
}
function SetCategriesMenuOnClick() {
    $(".cat_1_level a.level_1_link").click(function() {
        var bStateValue = $(this).parent().hasClass('expanded');
        if (!bStateValue) {
            $(".cat_1_level.expanded").find('div.subMenu').slideToggle("normal");
            $(".cat_1_level.expanded").addClass('collapsed');
            $(".cat_1_level.expanded").removeClass('expanded');
            FillChildCategories($(this));
        }
        else {
            $(this).parent().find('div.subMenu').slideToggle("normal");
            $(this).parent().removeClass('expanded');
            $(this).parent().addClass('collapsed');
        }
        return false;
    });
}
function FillChildCategories(obj) {
    if ($(obj).parent().find("ul li").length == 0) {
        timeOut = setTimeout("$('#img_CLoading_" + $(obj).attr("value") + "').show();", 500);
        $.wsAjax({
            url: (urlPrefix + "services/BookService.asmx/GetCategoriesChilds"),
            data: function() {
                return {
                    CategoryId: $(obj).attr("value")
                }
            },
            success: function(result) {
            clearTimeout(timeOut);
                $('#img_CLoading_' + $(obj).attr("value")).hide();                
                if (!result || result == "") {
                    //Error
                    alert("Uh oh, there was a problem.  " + result);
                }
                else {
                    $(obj).parent().find("ul").html(result);
                    $(obj).parent().find('div.subMenu').slideToggle("normal");
                    $(obj).parent().addClass('expanded');
                    $(obj).parent().removeClass('collapsed');
                }
            }
        });
    }
    else {
        $(obj).parent().find('div.subMenu').slideToggle("normal");
        $(obj).parent().addClass('expanded');
        $(obj).parent().removeClass('collapsed');
    }
}

function SetSearchBarValues() {
    var cid = $.url.param("cid");
    if (cid != "")
        $('#label_SearchBar select').val(cid)
    var text = $.url.param("text");
    if (text != "")
        $('#txtSearch').val(text)
    var type = $.url.param("type");
    if (type != "")
        $('input[value=' + type + ']').attr("checked", "checked");
}
function NotUser() {
    Master_SignOut(true);
}
function Master_SignOut(GoToLogin) {
        $.ajax({
            url: ("/services/UserService.asmx/Logout"),
            success: function() {
                if (GoToLogin)
                    $.goTo("/login.aspx");
                else
                    window.location.reload(true);
            }
        });
}

function OnEnter(e, buttonJQueryID) {    
    var keycode = null;
    if (!e) e = window.event
    if (e.keyCode) keycode = e.keyCode;
    else if (e.which) keycode = e.which;
    if (keycode == 13) {
        if (e.cancelBubble != null)
            e.cancelBubble = true;
        if (e.stopPropagation)
            e.stopPropagation();
        if (e.preventDefault)
            e.preventDefault();
        if (window.event)
            e.returnValue = false;
        if (e.cancel != null)
            e.cancel = true;
        e.returnValue = false;
        e.cancel = true;
        $(buttonJQueryID).click();
    }
}
function OnEnterF(e, f) {
    var keycode = null;
    if (!e) e = window.event
    if (e.keyCode) keycode = e.keyCode;
    else if (e.which) keycode = e.which;
    if (keycode == 13) {
        if (e.cancelBubble != null)
            e.cancelBubble = true;
        if (e.stopPropagation)
            e.stopPropagation();
        if (e.preventDefault)
            e.preventDefault();
        if (window.event)
            e.returnValue = false;
        if (e.cancel != null)
            e.cancel = true;
        e.returnValue = false;
        e.cancel = true;
        f();
    }
}
function SendActivationEmail() {
    $("#img_LoadSendActivation").show();
    $.wsAjax({
        url: (urlPrefix + "services/UserService.asmx/SendConfirmation"),
        data: function() {
            return {
                email: $.url.param("e")
            }
        },
        success: function(result) {
            $.goTo("/confirm-resent.aspx");
            $("#img_LoadSendActivation").hide();
        }
    });        
}
function GetCategoryBooksAjax(Id) {
    if (CurrentCategoryGuid != Id) {
        GetNewVerticalSponsors("#SponsorsBar ul", Id);
        $.wsAjax({
            url: (urlPrefix + "services/BookService.asmx/GetBrowseBooksHtml"),
            data: function () {
                return {
                    CategoryId: Id
                }
            },
            success: function (result) {
                if ($(".div_BookListContent").length > 0) {
                    $(".div_BookListContent").html(result[0]);
                    GetNewHorizontalSponsors(".div_CategorySponsors > div", Id, false);
                    //$(".headerCategory").text($("#h1_CategoryTitle").text());
                    var sHref = result[1];
                    $(".headerCategory").html("<h2><a href='/Browse/" + sHref + "'>" + $("#h1_CategoryTitle").text() + "</a></h2>");
                    CurrentCategoryGuid = Id;
                    $('.newBook').prepend("<span id='newBookIcon'></span>");

                    GetNewSecondChances(Id);
                }
                else {
                    //$.goTo("/confirm-resent.aspx"); 
                }

                //$("#img_LoadSendActivation").hide();
            }
        });
    }
}

function GetNewSecondChances(Id) {
    $.wsAjax({
        url: ('/services/SponsorService.asmx/GetAJAXSecondChances'),
        data: function () {
            return {
                SponsorAds: '',
                CategoryId: Id,
                CountryId: ClientCountryVisitLogId,
                ClientTimeZone: ClientTimeZone,
                VisitLogId: ClientVisitLogId
            }
        },
        success: function (result) {
            if (result.Status == 1) {
                if (result.SecondChances != "") {
                    $(".div_MainSecondChances").show();
                    $('#SCListContainer ul').html(result.SecondChances);
                    CreateCarouselLite();
                }
                else {
                    //Hide Second Chances
                    $(".div_MainSecondChances").hide();
                }
            }
            else {
            }
        }
    });
}

var listHorzAds;var iHorzAdIndex;
function GetNewHorizontalSponsors(hSelector, cId, bFromRefreshWishList) {
    //return;
    var r = Math.random();
    var IsFirst = true;
    iHorzAdIndex = 0;
    listHorzAds = $(".div_BookListContent .sponsorRow");
    GetSingleHorzAd(listHorzAds[0], hSelector, cId, IsFirst, bFromRefreshWishList);
}
function GetSingleHorzAd(obj, hSelector, cId, IsFirst, bFromRefreshWishList) {
    var r = Math.random();
    var newCId;
    $(obj).load('/handlers/GetSponsorAds.ashx?CTZ=' + ClientTimeZone + '&isf=' + IsFirst + '&r=' + r + '&type=Categories&i=' + iMaxAdsInHorizontalBar + '&CID=' + cId + '&SAL=1 li', null,
                    function(result) {
                        if (result == "") {
                            if (bFromRefreshWishList) {
                                if (iHorzAdIndex < listHorzAds.length) {
                                    newCId = $(obj).parent().attr('NextCId');
                                    $(obj).remove();
                                    iHorzAdIndex++;
                                    GetSingleHorzAd(listHorzAds[iHorzAdIndex], hSelector, newCId, false, bFromRefreshWishList);
                                }
                            }
                            else {
                                $(".div_BookListContent .Empty101Ad").remove();
                            }

                        }
                        else {
                            newCId = $(obj).parent().attr('NextCId');
                            $(hSelector + " ul").html(result);                            
                            var c = $(hSelector).html();
                            $(obj).removeClass("Empty101Ad");
                            $(obj).html("<div class='HorizontalSponsors'>" + c + "</div>");
                            iHorzAdIndex++;
                            if (bFromRefreshWishList)
                                GetSingleHorzAd(listHorzAds[iHorzAdIndex], hSelector, newCId, false, bFromRefreshWishList);
                            else
                                GetSingleHorzAd(listHorzAds[iHorzAdIndex], hSelector, cId, false, bFromRefreshWishList);
                        }
                    });
}


function GetNewVerticalSponsors(hSelector, cId) {
    var r = Math.random();
    $(hSelector).load('/handlers/GetSponsorAds.ashx?CTZ=' + ClientTimeZone + '&r=' + r + '&type=global&i=' + iMaxAdsInSideBar + '&CID=' + cId + '&SAL=2 li', null, null);
}
$.extend({ URLEncode: function(c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});

function ShowChancesBarWarning() {
    $("#ChancesBar_TicketsMessage").hide();
    $("#ChancesBar_WarningMessage").show();
}

function HideChancesBarWarning() {
    $("#ChancesBar_TicketsMessage").show();
    $("#ChancesBar_WarningMessage").hide();
}
function CreateThemedRecaptcha(id) {
    Recaptcha.create("6LfhoggAAAAAAOstDudMt0SawJtnvb6Hg5wL6qdU",
        id, {
            theme: "red"
        });
}
function ConfigureFaceBookLike() {
    window.fbAsyncInit = function () {
        FB.init({ appId: '123751810969049', status: true, cookie: true,
            xfbml: true
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());
}

