﻿function master_onload() {
    LoadSearchMain();
    jQuery("#addtofavorites").jBrowserBookmark();
    jQuery.Language_pop();
    jQuery.MyBasket_pop();
    FillBasket(new cookieList("myBasket").items());
    MotBubbleSettings();
    fixInputVal();
    //addBasketIcon();
    SendToFriendMain();
    jQuery("#ui-datepicker-div").hide();
    if (jQuery.browser.version == "7.0") {
        jQuery(".slm-layout-main").each(function () {
            if (jQuery(this).children(".dfwp-column").length == 2) {
                jQuery(this).children(".dfwp-column").first().css("width", "49%");
                jQuery(this).children(".dfwp-column").last().css("width", "50%");
            }
        });
    }

}

function fixInputVal() {
    (function (jQuery) {

        jQuery('.inputVal').each(function () {
            var currentVal = this.value;
            jQuery(this).focus(function () {
                if (this.value == currentVal) {
                    this.value = '';
                }
            });
            jQuery(this).blur(function () {
                if (this.value == '') {
                    this.value = currentVal;
                }
            });
        });
    })(jQuery);


}

var cookieList = function (cookieName) {

    var cookie = jQuery.cookie(cookieName);
    var items = cookie ? cookie.split(/,/) : new Array();

    return {
        "add": function (val) {
            items.push(val);
            var _path = getSitePath();
            jQuery.cookie(cookieName, items, { expires: 366, path: _path }); //'/' 
        },
        "clear": function () {
            jQuery.cookie(cookieName, null);
        },
        "items": function () {
            return items;
        },
        "deleteContent": function () {
            items = null;
            var _path = getSitePath();
            jQuery.cookie(cookieName, items, { expires: -1, path: _path });
        }
    }
}

function getSitePath() {
    var ind = window.location.pathname.substring(1).indexOf('/') + 2;
    return window.location.pathname.substring(0, ind);
}

function addBasketIcon() {

    jQuery("[basket]").each(function () {
        var width = jQuery(this).find("img").width() - 15;
        var top = jQuery(this).find("img").height() - 15;
        jQuery(this).css("position", "relative");
        var url = jQuery(this).get(0).href;
        var altText = jQuery("input[id*=_AddToBasket]").val();

        var element = jQuery('<a href="#" alt="' + altText + '" title="' + altText + '" class="MyBasketPlus"><img src="/_Layouts/Images/MOT/General/plus.gif" alt""/></a>');
        element.click(function () {
            return addBasketClick(url);
        });

        jQuery(element).css("top", top + "px")
        if (jQuery(this).css("direction") == "ltr") {
            jQuery(element).css("left", width + "px")
        }
        else {
            jQuery(element).css("right", width + "px")
        }
        jQuery(this).append(jQuery(element));
    });
}
function addBasketClick(url) {
    var myBasketlist = new cookieList("myBasket");
    var isExists = false;
    var items = myBasketlist.items();
    jQuery(items).each(function (index) {
        if (this.toString() == url) {
            isExists = true;
        }
    });
    if (isExists == false) {
        myBasketlist.add(url);
        FillBasket(items);
    }
    return false;
}
function FillBasket(items) {
    jQuery('#basketlistcounter').text(items.length);
    var innerhtml = "";
    for (i = 0; i < items.length; i++) {
        var title = GetTitle(items[i]);
        innerhtml = innerhtml + "<div class='BasketLink'><a target='_blank' href='" + items[i] + "' class='BasketLinkItem' title='" + title + "'>" + title.replace(/%20/g, " ").replace(/%27/g, "'") + " &#187;</a></div>";
    }
    jQuery('.Basket').html(innerhtml);
}
function GetTitle(url) {
    var value = url.toLowerCase();
    if (value.lastIndexOf(".aspx") > -1)
        value = url.substring(value.lastIndexOf("/") + 1, value.lastIndexOf(".aspx"));
    else if (value.lastIndexOf('/') + 1 == value.length) {
        value = url.substring(0, value.lastIndexOf("/"));
        value = value.substring(value.lastIndexOf("/") + 1);
    }
    else
        value = url.substring(value.lastIndexOf("/") + 1);

    return value;
}

jQuery(document).ready(function () {
    jQuery('.online-tools').parent().addClass("Float");
    jQuery('.usefull-tips').parent().addClass("Float");
    jQuery("a[disabled='disabled']").addClass("aDisabled");
    if (jQuery('HTML')[0].dir == 'rtl') {
        var removeText = '';
        var baseElement = jQuery('.pager span:first-child a:first-child');
        var nextElement = baseElement.next();
        if (nextElement.length != 0 && nextElement.html().indexOf("...") > -1) {
            baseElement = baseElement.next();
        }
        jQuery(jQuery('.pagerNum').get()).each(function (i) { baseElement.after(this).after('&nbsp;'); removeText += '&nbsp;' });
        if (jQuery('.pager').length > 0) { jQuery('.pager').html(jQuery('.pager').html().replace(removeText, '')); }
    };
});

function ValidInput(source, arguments) {
    if (arguments.Value == '')
        result = true;
    else
        result = !RegexCheck("<[^>]*>|script", arguments.Value)

    arguments.IsValid = result;
}

function RegexCheck(pat, val) {
    result = false;
    if (pat != null) {
        var regEx = new RegExp(pat, "gi");
        result = regEx.test(val);
    }

    return result;
}

function RepairingPublishingUrl() {
    jQuery("span[id$=_RichLinkField_LinkFieldDisplay] > a").each(function () {
        if (jQuery(this).html() == "") {
            jQuery(this).html("Edit display link");
        }
    });
}

function clearSearchFilter() {

    jQuery("div.blueBox input:text").val("")
    jQuery("div.blueBox select").val(0)
    jQuery("div.blueBox input:checkbox").removeAttr('checked')

    //only fo cities
    jQuery("select[id$=CityDropDownList]").attr("disabled", "disabled");
}

function AccumulatorLoad() {
    if (jQuery.browser.msie && jQuery.browser.version == "7.0") {
        jQuery('.ImageAndLinkTitle_Component').removeClass('Float').parent().addClass('Float');
        jQuery('.AccumulatorThreeColumns').parent().addClass('AccumulatorThreeColumnsParent');
    }
}

function RemoveEmptyTitle() {
    jQuery("h3").each(function () {
        if (jQuery(this).html() == "") {
            jQuery(this).css("display", "none");
        }
    });
}

////--------------------------Main search--------------------------///////
function LoadSearchMain() {
    jQuery('#quickSearchTextBox').keyup(function (event) {
        var previousSelected = quickSearchSelectedDivIndex;
        var searchAgain = true;
        // catch some keys
        switch (event.keyCode) {
            case 13:
                searchAgain = false;
                break;
            case 38:    // key up
                quickSearchSelectedDivIndex--;
                var selectText = jQuery("#quickSearchResults>div:eq(" + quickSearchSelectedDivIndex + ")").text();
                if (selectText != "") {
                    jQuery("#quickSearchTextBox").val(selectText);
                    searchAgain = false;
                }
                break;
            case 40:    // key down
                quickSearchSelectedDivIndex++;
                var selectText = jQuery("#quickSearchResults>div:eq(" + quickSearchSelectedDivIndex + ")").text();
                if (selectText != "") {
                    jQuery("#quickSearchTextBox").val(selectText);
                    searchAgain = false;
                }
                break;
        }

        // check bounds
        if (quickSearchSelectedDivIndex != previousSelected) {
            if (quickSearchSelectedDivIndex < 0)
                quickSearchSelectedDivIndex = 0;
            if (quickSearchSelectedDivIndex >= jQuery("#quickSearchResults>div").length - 1)
                quickSearchSelectedDivIndex = jQuery("#quickSearchResults>div").length - 1;
        }

        // select new div, unselect the previous selected
        if (quickSearchSelectedDivIndex > -1) {
            if (quickSearchSelectedDivIndex != previousSelected) {
                unSelectDiv(jQuery("#quickSearchResults>div:eq(" + previousSelected + ")"));
                selectDiv(jQuery("#quickSearchResults>div:eq(" + quickSearchSelectedDivIndex + ")"));
            }
        }

        // if the query is different from the previous one, search again
        if (searchAgain == true) {
            if (jQuery('#quickSearchTextBox').data("query") != jQuery('#quickSearchTextBox').val()) {
                if (quickSearchTimer != null) // cancel the delayed event
                    clearTimeout(quickSearchTimer);
                quickSearchTimer = setTimeout(function () { // delay the searching
                    jQuery("#quickSearchResults").fadeOut(200, initSearch);
                }, quickSearchConfig.delay);
            }

        }
    });
}

function unSelectDiv(div) {
    // first stop all animations still in progress
    jQuery("#quickSearchResults>div>div").stop(true, true);

    div.removeClass("quickSearchResultDivSelected").addClass("quickSearchResultDivUnselected");
    jQuery("#details", div).hide();
}

function selectDiv(div) {
    div.addClass("quickSearchResultDivSelected");
    jQuery("#details", div).slideDown(quickSearchConfig.resultAnimation);
}

function initSearch() {
    // first store query in data
    jQuery('#quickSearchTextBox').data("query", jQuery('#quickSearchTextBox').val());

    // clear the results
    jQuery("#quickSearchResults").empty();

    // start the search
    var query = jQuery("#quickSearchTextBox").val();
    if (query.length >= quickSearchConfig.minCharacters) {
        showResultsDiv("Searching ..."); // display status
        search(query);
    }
}

function search(query) {
    quickSearchSelectedDivIndex = -1;
    var queryXML = [];
    queryXML.push("<QueryPacket xmlns='urn:Microsoft.Search.Query'>")
    queryXML.push("<Query>");
    queryXML.push("<SupportedFormats><Format>urn:Microsoft.Search.Response.Document.Document</Format></SupportedFormats>");
    queryXML.push("<Context>");
    queryXML.push("<QueryText language=\"" + quickSearchConfig.scope + "\" type=\"MSSQLFT\">SELECT Title,Rank,Description,Path FROM SCOPE() WHERE \"Scope\" = '" + quickSearchConfig.scope + "' AND CONTAINS(Title,'\"" + query + "*\"') AND NOT CONTAINS(Path,'\"DispForm.aspx*\"') ORDER BY \"Rank\"</QueryText>");
    queryXML.push("</Context>");
    queryXML.push("<Range><StartAt>1</StartAt><Count>" + quickSearchConfig.numberOfResults + "</Count></Range>");
    queryXML.push("<TrimDuplicates>true</TrimDuplicates>")
    queryXML.push("</Query></QueryPacket>");

    var soapEnv =
            "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
              <soap:Body> \
                <Query xmlns='urn:Microsoft.Search'> \
                  <queryXml>" + escapeHTML(queryXML.join("")) + "</queryXml> \
                </Query> \
              </soap:Body> \
            </soap:Envelope>";

    jQuery.ajax({
        url: "/_vti_bin/search.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });

    function processResult(xData, status) {
        var html = [];
        jQuery(xData.responseXML).find("QueryResult").each(function () {
            var divWidh = jQuery("#quickSearchTextBox").width();

            var x = jQuery("<xml>" + jQuery(this).text() + "</xml>");
            x.find("Document").each(function () {
                var title = jQuery(this).find("Value").first().text();
                //var url = jQuery(this).find("Value").last().text();

                html.push("<div class='quickSearchResultDivUnselected' style='width:" + divWidh + "px;max-width:" + divWidh + "px' onclick='javascript:SetSearchSelectedDivIndex(jQuery(this));' onmouseover='javascript:selectDiv(jQuery(this));' onmouseout='javascript:unSelectDiv(jQuery(this));'>" + title + "</div>");
            });
        });
        jQuery("#quickSearchResults").empty().append(html.join(""));
        jQuery("#quickSearchResults>div>a").hover(
                function () { selectDiv(jQuery(this).parent()); },
                function () { unSelectDiv(jQuery(this).parent()); }
            );
        showResultsDiv();
    }
}

function escapeHTML(str) {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function PerformSearch(EmptyMessage, PageResultUrl, TextEmptyError) {
    var freetext = jQuery("#quickSearchTextBox").val();
    if (freetext != "" && freetext != EmptyMessage) {
        var sSearchUrl = PageResultUrl + "?k=" + escape(freetext);
        document.location.href = sSearchUrl;
    }
    else {
        alert(TextEmptyError);
    }
}

function SetSearchSelectedDivIndex(div) {
    var selectText = div.text();
    if (selectText != "") {
        jQuery("#quickSearchTextBox").val(selectText);
    }
}

////---------------Basket----------------/////////////
function ClearBasket() {
    var myBasket = new cookieList("myBasket");
    myBasket.deleteContent();
    jQuery('.Basket_popWrap').hide();
    FillBasket(new cookieList("myBasket").items());
}
function OpenSendPanel() {
    jQuery('.BasketSendButton').hide();
    jQuery('.BasketCloserDiv').show();
    jQuery('.BasketSendToMail').show();
    //event.stopPropagation();
}

function sendLinksToMail_Click(CurrentLCID) {
    var validationResult = Page_ClientValidate("SendBasket");
    if (validationResult) {
        jQuery.post("/_layouts/Email/Sender.ashx", { requestType: "BasketLinksMail",
            comments: jQuery(".Basket").html(),
            sendTo: jQuery(".basketSenderMailText").val(),
            userlcid: CurrentLCID
        }, function (data) { AnswerBasket(data); });
        //event.stopPropagation();
    }
    //return false;
}

function AnswerBasket(data) {
    jQuery('.BasketSendMessage').show();
    jQuery('.BasketSendToMail').hide();

    if (data.IsSuccess) {
        jQuery('#SendMailMessage').html(data.Success);
    }
    else {
        jQuery('#SendMailMessage').html(data.Fail);
    }
}

/////---------------- ActionLinksBar -------------///////////// 
function FriendlyPrint_onclick() {
    try {
        var objWidth = jQuery("#MainContentToPrint").width();
        var disp_setting = "toolbar=no,directories=no,menubar=no,";
        disp_setting += "width=" + (objWidth + 100) + ", height=500,scrollbars=yes,left=100, top=25,resizable=no,location=yes";
        window.open("/_layouts/MOT/Print.aspx?lang=" + window.document.documentElement.lang, "FreindlyPrint", disp_setting, false);  //"Freindly Print", disp_setting, false);
    }
    catch (e) {
    }
}
function SendMailtoFriend() {
    var tit = document.getElementsByTagName("title").length > 0 ? document.getElementsByTagName("title")[0].innerHTML : "";
    var cData = { type: 'FriendlyPrint', url: jQuery(location).attr('href'), sub: tit };
    SendMailtoFreind_onclick(cData);
}

///----------------- SendToFriend ---------------////////
function SendToFriendMain() {
    jQuery('.inputCommentsText').keyup(function () {
        checkLength(this, 256);
    }).bind('paste', function () { checkLength(this, 256); });

    var refress = jQuery('.LBD_CaptchaIcons').children('a')[1];
    jQuery(refress).click(function () {
    });
}
function checkLength(sender, maxLength) {
    if (jQuery(sender).val().length > maxLength) {
        jQuery(sender).val(jQuery(sender).val().substr(0, maxLength));
    }
}

function SendMailtoFreind_onclick(cData) {
    Clear_onclick();
    jQuery('.SendMail_btn').data('cData', cData);
    jQuery.blockUI({
        message: jQuery('#SendMailForm'),
        fadeIn: 1000,
        overlayCSS: ({ backgroundColor: "#c5c7c9", cursor: "" }),
        css: { cursor: "",
            margin: 0,
            width: '480px',
            top: '10%',
            left: (jQuery("form").width() - 480) / 2,
            textAlign: 'inherit',
            color: '#393838',
            border: 'none'
        }
    });
    jQuery('.linkbtn_Close').click(function () {
        jQuery.unblockUI({ fadeOut: 1000 }
                );
        setTimeout(Clear_onclick, 1000);
    });
}
function Clear_onclick() {
    jQuery('#pnl_SendMailFormContent').show();
    jQuery('#pnl_SendMailMessage').hide();
    jQuery('#SendMailMessageText').html("");
    jQuery('#CapthaError').html("");
    jQuery('#audiospan').html("");

    jQuery('.SendMailFormContent input[type=text], textarea').val('');
}
function SendMail_onclick(sender, event, CurrentLCID) {
    var validationResult = Page_ClientValidate("SendToFriend");

    if (validationResult) {
        var cData = jQuery(sender).data('cData');
        jQuery.post("/_layouts/Email/Sender.ashx", { requestType: cData.type,
            userlcid: CurrentLCID,
            pageurl: cData.url,
            subject: cData.sub,
            senderName: jQuery(".inputSenderNameText").val(),
            senderMail: jQuery(".inputSenderMailText").val(),
            sendTo: jQuery(".inputSendToMailText").val(),
            comments: jQuery(".inputCommentsText").val(),
            captcha_id: jQuery('.cinputtext').attr('id'),
            captcha_val: jQuery('.cinputtext').val(),
            captchaImage_src: jQuery('.captchaImage').attr('src'),
            random: Math.floor(Math.random() * 9999999)
        }, function (data) { Answer(data); });
    }
    //event.stopPropagation();
    return false;
}

function Answer(data) {
    setTimeout("refresh()", 5);

    if (!data.CaptchaIsValid) {
        jQuery('#CapthaError').html(data.CaptchaErrorText);
        jQuery('.cinputtext').val('');
        setTimeout(function () {
            jQuery('.cinputtext').focus(function () {
                jQuery('#CapthaError').html('');
                jQuery(this).unbind("focus");
            });
        }, 500);
    }
    else if (data.IsSuccess) {
        jQuery('#pnl_SendMailFormContent').hide();
        jQuery('#pnl_SendMailMessage').show();

        jQuery('.suc').show();
        jQuery('.err').hide();

        jQuery('#SendMailMessageText').html(data.Success);
    }
    else {
        jQuery('#pnl_SendMailFormContent').hide();
        jQuery('#pnl_SendMailMessage').show();

        jQuery('.suc').hide();
        jQuery('.err').show();

        jQuery('#SendMailMessageText').html(data.Fail);
    }
}

jQuery("div.SendMailFormFooter_btn").mouseover(function () {
    jQuery(this).children('.btnRight').addClass('btnRight-hover');
    jQuery(this).children('.btnMiddle').addClass('btnMiddle-hover');
    jQuery(this).children('.btnLeft').addClass('btnLeft-hover');
}).mouseout(function () {
    jQuery(this).children('.btnRight').removeClass('btnRight-hover');
    jQuery(this).children('.btnMiddle').removeClass('btnMiddle-hover');
    jQuery(this).children('.btnLeft').removeClass('btnLeft-hover');
});

function MotBubbleSettings() {

    (function ($) {
        //create bubble popups for each element with class "button"
        $('.Explain').CreateBubblePopup();

        //set customized mouseover event for each button
        $('.Explain').mouseover(function () {

            //show the bubble popup with new options
            $(this).ShowBubblePopup({
                innerHtml: $(this).attr('Explaination'),
                innerHtmlStyle: {
                    color: '#676767',
                    'text-align': 'right',
                    width: '200px'
                },
                themeName: 'grey',
                themePath: '/_layouts/images/MOT/jquerybubblepopup-theme',
                afterShown: function () {
                    if ($('html').attr('dir') == 'rtl') {
                        var middleStyleRight = $(".jquerybubblepopup-middle-right").attr('style').replace('right', 'left');
                        $(".jquerybubblepopup-middle-right").attr('style', middleStyleRight);
                        var middleStyleLeft = $(".jquerybubblepopup-middle-left").attr('style').replace('left', 'right');
                        $(".jquerybubblepopup-middle-left").attr('style', middleStyleLeft);

                        var bottomStyleRight = $(".jquerybubblepopup-bottom-right").attr('style').replace('right', 'left');
                        $(".jquerybubblepopup-bottom-right").attr('style', bottomStyleRight);
                        var bottomStyleLeft = $(".jquerybubblepopup-bottom-left").attr('style').replace('left', 'right');
                        $(".jquerybubblepopup-bottom-left").attr('style', bottomStyleLeft);

                        var topStyleRight = $(".jquerybubblepopup-top-right").attr('style').replace('right', 'left');
                        $(".jquerybubblepopup-top-right").attr('style', topStyleRight);
                        var topStyleLeft = $(".jquerybubblepopup-top-left").attr('style').replace('left', 'right');
                        $(".jquerybubblepopup-top-left").attr('style', topStyleLeft);
                    }
                }
            });

            if ($('html').attr('dir') == 'rtl') {
                var middleStyleRight = $(".jquerybubblepopup-middle-right").attr('style').replace('right', 'left');
                $(".jquerybubblepopup-middle-right").attr('style', middleStyleRight);
                var middleStyleLeft = $(".jquerybubblepopup-middle-left").attr('style').replace('left', 'right');
                $(".jquerybubblepopup-middle-left").attr('style', middleStyleLeft);

                var bottomStyleRight = $(".jquerybubblepopup-bottom-right").attr('style').replace('right', 'left');
                $(".jquerybubblepopup-bottom-right").attr('style', bottomStyleRight);
                var bottomStyleLeft = $(".jquerybubblepopup-bottom-left").attr('style').replace('left', 'right');
                $(".jquerybubblepopup-bottom-left").attr('style', bottomStyleLeft);

                var topStyleRight = $(".jquerybubblepopup-top-right").attr('style').replace('right', 'left');
                $(".jquerybubblepopup-top-right").attr('style', topStyleRight);
                var topStyleLeft = $(".jquerybubblepopup-top-left").attr('style').replace('left', 'right');
                $(".jquerybubblepopup-top-left").attr('style', topStyleLeft);
            }
        });
    })(jQuery);
}
