﻿//Register an alias to the telerik jQuery prefix
Sys.Application.add_load(function() { window.$ = $telerik.$; });

// function for generating the url in case of language change
function generateNewLanguagePageUrl(langSelectorID, currentLang) {
    var langSelectorObject = document.getElementById(langSelectorID);
    var newLangCode;
    var newUrl;
    var lang;
    if (langSelectorObject != null) {
        var newLangCode = langSelectorObject.control.get_value();
        if (newLangCode != null) {
            newUrl = window.location.href;
            if (newUrl.indexOf("/" + currentLang + "/") > 0) {
                newUrl = newUrl.replace("/" + currentLang + "/", "/" + newLangCode + "/");
            } else {
                newUrl = addReplaceURLStringParameter(newUrl, "lang", newLangCode);
            }
        }
    }
    return newUrl;
}

// function for generating the url in case of language change
function generateNewCurrencyPageUrl() {
    var newUrl;
    newUrl = window.location.href;
    newUrl = removeURLStringParameter(newUrl, "CR");

    return newUrl;
}

// function for changing pages (accommodation list/search result/brochures/etc)
function changePageNumber(newPage) {
    var newUrl = window.location.href;
    newUrl = addReplaceURLStringParameter(newUrl, "page", newPage);
    window.location.href = newUrl;
}


//function for printing the current page
function printPage() {
    this.window.print();
}

function openProductDetails(anchorObj, rowId, progressId, imageId, openImage, closeImage) {
    openProductDetails(anchorObj, rowId, progressId, imageId, openImage, closeImage, false);
}

function openProductDetails(anchorObj, rowId, progressId, imageId, openImage, closeImage, forceOpen) {

    var rowObject = $get(rowId);
    var progressObject = $get(progressId);
    var imageObject = $get(imageId);
    var isOpen = "";

    if (rowObject.className == "" && !forceOpen) {
        rowObject.className = "noDisplay"
        imageObject.src = openImage;
        isOpen = "";
    } else {
        rowObject.className = "";
        imageObject.src = closeImage;
        isOpen = "1";
    }

    if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
        Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
    }

    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(showUpdateProgress);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(hideUpdateProgress);

    function showUpdateProgress(sender, args) {
        progressObject.style.display = 'block';
    }

    function hideUpdateProgress(sender, args) {
        if (args.get_response().get_aborted()) {
            // reset the conteiner state
            rowObject.className = "noDisplay";
            progressObject.style.display = 'none';
            imageObject.src = openImage;


        } else {
            progressObject.style.display = 'none';
            if (forceOpen) rowObject.scrollIntoView();
        }
        Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(showUpdateProgress);
        Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(hideUpdateProgress);

    }
    // make post back with apropriate arguments
    var id = anchorObj.id.replace(/_/g, "$");
    __doPostBack(id, isOpen);

}




//function to open a page in lytebox window
function openLyteBoxSize1(url) {
    var a = document.createElement("a");
    a.href = url;
    a.rel = "lyteframe";
    //a.title = title;
    a.rev = "width: 480px; height: 300px; scrolling: no;";
    var oWnd = radopen("http://dir.bg", null);
    oWnd.setSize(480, 300);
    oWnd.set_visibleStatusbar(false);
    oWnd.center();
    //myLytebox.start(a, false, true);
}
function openLyteBox(url, width, height, e) {
//    var oWnd = $find("ctl00_rwDetails");
//    oWnd.setUrl(url);
//    oWnd.set_title("");
//    oWnd.show();
   // debugger;
    var oWnd = radopen(url, null);
    oWnd.set_behaviors(Telerik.Web.UI.WindowBehaviors.Resize + Telerik.Web.UI.WindowBehaviors.Close)
    oWnd.setSize(width, height);
    oWnd.set_visibleStatusbar(false);
    oWnd.center();
    var bounds = oWnd.getWindowBounds();
    if (top != self) {
        //frame
        var docHeight = $telerik.$(document).height();
        var iframeHeight = $telerik.$(window).height();
        if (iframeHeight == docHeight) {
            // frame with scrolls
            //alert(document.clientHeight + " " + document.scrollHeight);
            var ypos = e.clientY - (bounds.height / 2);
            oWnd.moveTo(bounds.x, ypos);
            bounds.y = ypos;
        }
    }
    if (bounds.y < 0) {
        oWnd.moveTo(bounds.x, 10);
    }   
}

function openPopupSize1(url) {
    openPopup(url, 480, 300);
}
function openPopup(url, width, height) {
    var name = url.replace(/\./g, "").replace(/\,/g, "").replace(/\:/g, "").replace(/\//g, "").replace(/\?/g, "").replace(/\=/g, "").replace(/\&/g, "").replace(/\-/g, "");
    window.open(url, name, "width=" + width + ",height=" + height + ",location=0,menubar=0,resizable=0,status=0,titlebar=0,toolbar=0", true);
}

function showDayOfWeekName(containerId, dayOfWeekIndex) {

    var containerObj = document.getElementById(containerId);
    containerObj.innerHTML = DaysOfWeekArray[dayOfWeekIndex];
}


function OnDateSelected(sender, e) {
    var date = e.get_newDate();
    var firstDayOfWeek = sender.get_calendar()._firstDayOfWeek
    if (date != null) {
        dayIndex = date.getDay()
        showDayOfWeekName(sender.get_dayOfWeekControlID(), dayIndex);
    }
}

function onCheckBoxClick(chk, ddlId, cbxName, dlsName, lblName) {
    var combo = $find(ddlId);
    //prevent second combo from closing
    cancelDropDownClosing = true;
    //holds the text of all checked items
    var text = "";
    //holds the values of all checked items
    var values = "";
    //get the collection of all items
    var items = combo.get_items();
    //enumerate all items
    for (var i = 0; i < items.get_count(); i++) {
        var item = items.getItem(i);
        //get the checkbox element of the current item
        var lp = 0;
        var chkNum = "00";
        var chk1, lbl;
        do {
            chk1 = $get(combo.get_id() + "_i" + i + "_" + dlsName + "_ctl" + chkNum + "_" + cbxName);
            if (chk1 != null) {
                if (chk1.checked) {
                    //var lbl = $get(combo.get_id() + "_i" + i + "_" + dlsName + "_ctl" + chkNum + "_" + lblName);
                    var lbl = $telerik.getNextHtmlNode(chk1);
                    //var lbl = $get("_rfdSkinned" + combo.get_id() + "_i" + i + "_" + dlsName + "_ctl" + chkNum + "_" + cbxName);
                    if (lbl != null) {
                        text += lbl.innerHTML + ",";
                        values += chk1.value + ","; ;
                    }
                }
                lp = lp + 1;
                chkNum = pad(lp);
            }

        } while (chk1 != null);
    }
    //remove the last comma from the string
    text = removeLastComma(text);
    values = removeLastComma(values);
    if (text.length > 0) {
        //set the text of the combobox
        combo.set_text(text);
        combo.set_value(values);
    }
    else {
        //all checkboxes are unchecked
        //so reset the control
        combo.set_text("");
    }
}




//this method removes the ending comma from a string
function removeLastComma(str) {
    return str.replace(/,$/, "");
}

function pad(inte) {
    return inte = (inte < 10) ? '0' + inte : inte;
}

// function to prevent closing of telerik dropdown control
function stopPropagation(e) {
    e.cancelBubble = true;
    if (e.stopPropagation) {
        e.stopPropagation();
    }
}


function openAccommodationSearchDetailPanel(anchorObj, rowId, progressId, imageId, openImage, closeImage) {

    var rowObject = $get(rowId);
    var imageObject = $get(imageId);
    var isOpen = "";

    if (rowObject.className == "") {
        imageObject.src = openImage;
        rowObject.className = "noDisplay"
        isOpen = "";
    } else {
        imageObject.src = closeImage;
        rowObject.className = "";
        isOpen = "1";
    }
    var progressObject = $get(progressId);


    if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
        Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
    }

    if (isOpen == "1") {
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(showUpdateProgress);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(hideUpdateProgress);
    }

    function showUpdateProgress(sender, args) {
        progressObject.style.display = 'block';
    }

    function hideUpdateProgress(sender, args) {
        if (args.get_response().get_aborted()) {
            // reset the conteiner state
            rowObject.className = "noDisplay";
            progressObject.style.display = 'none';
            imageObject.src = openImage;
        } else {
            progressObject.style.display = 'none';
        }
        Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(showUpdateProgress);
        Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(hideUpdateProgress);

    }
    // make post back with apropriate arguments
    var id = anchorObj.id.replace(/_/g, "$");
    __doPostBack(id, isOpen);
}

function highlightItems(sender, eventArgs) {
    sender.highlightAllMatches(sender.get_text());
}

function cancelLocationOpening(sender, eventArgs) {
    if (sender.get_text().length < 0) {
        eventArgs.set_cancel(true);
    }
}

function addHandler(obj, type, fn) {
    if (obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function() { obj['e' + type + fn](window.event); }
        obj.attachEvent('on' + type, obj[type + fn]);
    } else
        obj.addEventListener(type, fn, false);
}

function removeHandler(obj, type, fn) {
    if (obj.detachEvent) {
        obj.detachEvent('on' + type, obj[type + fn]);
        obj[type + fn] = null;
    } else
        obj.removeEventListener(type, fn, false);
}
function hideActivTooltip() {
    var activeToolTip = Telerik.Web.UI.RadToolTip.getCurrent();
    if (activeToolTip) activeToolTip.hide();
}



function DateEqual(date1, date2) {
    return (date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate())
}

function StartTimer(timerid) {
    var timer = $find(timerid);
    if (timer) {
        timer.set_enabled(true);
        timer._startTimer();
    }
}

function StopTimer(timerid) {
    var timer = $find(timerid);
    if (timer) {
        timer.set_enabled(false);
        timer._stopTimer();
    }
}

function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow)
        oWindow = window.radWindow;
    else if (window.frameElement.radWindow)
        oWindow = window.frameElement.radWindow;
    return oWindow;
}

Number.prototype.toCurrencyString = function(currencySymbol, decimalPlaces) {
    return this.formatPriceValue(currencySymbol + " ", DecimalSeparator, decimalPlaces);
}
Number.prototype.toPriceString = function() {
    return this.formatPriceValue("", DecimalSeparator, 2);
}
Number.prototype.formatPriceValue = function(currencySymbol, decimalSeparator, decimalDigits) {
    var n, startAt, intLen;
    var noFractions = false;
    var thousandsSeparator = "";
    n = this.round(noFractions ? 0 : decimalDigits, true, decimalSeparator);
    intLen = n.length - (noFractions ? 0 : 3);
    if ((startAt = intLen % 3) == 0) startAt = 3;
    for (var i = 0, len = Math.ceil(intLen / 3) - 1; i < len; i++) n = n.insertAt(i * 4 + startAt, thousandsSeparator);
    return currencySymbol + n;
}
Number.prototype.round = function(decimals, returnAsString, decimalSeparator) {
    //Supports 'negative' decimals, e.g. myNumber.round(-3) rounds to the nearest thousand     
    var n, factor, breakPoint, whole, frac;
    if (!decimals) decimals = 0;
    factor = Math.pow(10, decimals);
    n = (this.valueOf() + "");         //To get the internal value of an Object, use the valueOf() method 
    if (!returnAsString) return Math.round(n * factor) / factor;
    if (!decimalSeparator) decimalSeparator = ".";
    if (n == 0) return "0" + (decimalSeparator = 0 ? "" : "." + ((factor + "").substr(1)));
    breakPoint = (n = Math.round(n * factor) + "").length - decimals;
    whole = n.substr(0, breakPoint);
    if (whole == "") whole = "0";
    if (decimals > 0) {
        frac = n.substr(breakPoint);
        if (frac.length < decimals) frac = (Math.pow(10, decimals - frac.length) + "").substr(1) + frac;
        return whole + decimalSeparator + frac;
    } else return whole + ((Math.pow(10, -decimals) + "").substr(1));
}

String.prototype.insertAt = function(loc, strChunk) {
    return (this.valueOf().substr(0, loc)) + strChunk + (this.valueOf().substr(loc))
}

// Removes leading whitespaces
String.prototype.TrimLeft = function() {

    var re = /\s*((\S+\s*)*)/;
    return this.replace(re, "$1");

}

// Removes ending whitespaces
String.prototype.TrimRight = function() {

    var re = /((\s*\S+)*)\s*/;
    return this.replace(re, "$1");

}

// Removes leading and ending whitespaces
String.prototype.Trim = function() {
    return this.TrimLeft().TrimRight();
}


/* 
-------------------------------------------------------------------------------
Functions for manipulating URLs and query strings
	
Author: Nikolai Rangelov
----------------------------------------------------------------------------- */


/**
* Creates the URL with given parameters.
*
* @param path The full URL path.
* @param paramName The name of the parameter.
* @param paramValue The string-value of the parameter.
* @return The URL with appended parameter.
*/
function addURLParameter(url, paramName, paramValue) {
    if (urlHasParameter(url))
        url += "&";
    else
        url += "?";
    url += paramName;
    url += "=";
    url += paramValue;
    return url;
}


function urlHasParameter(url) {
    var strUrl = new String(url);
    if (url.indexOf('?') != -1)
        return true;
    else
        return false;
}


/*
Removes a parameter with its value from a query string
*/
function removeURLStringParameter(queryString, param) {
    var tmp, key;
    var startPos, endPos;

    tmp = new String("");
    key = new String("");

    if (queryString) tmp = queryString;
    if (param) key = param;

    startPos = tmp.indexOf(param, 0);
    if (startPos > 0) {
        endPos = tmp.indexOf("&", startPos);
        if (endPos == -1)
            tmp = tmp.substring(0, startPos)
        else
            tmp = tmp.substring(0, startPos) + tmp.substring(endPos + 1);
    }

    if (tmp.charAt(tmp.length - 1) == '?' || tmp.charAt(tmp.length - 1) == '&')
        tmp = tmp.substring(0, tmp.length - 1);

    return tmp;
}


/*
Add or replace a parameter with its value in a query string
*/
function addReplaceURLStringParameter(queryString, param, paramValue) {
    var tmp, key, value;
    var startPos, endPos;

    tmp = new String("");
    key = new String("");

    if (queryString) tmp = queryString;
    if (param) key = param;
    value = paramValue;

    if (key.length > 0) {
        startPos = tmp.indexOf(key, 0);
        if (startPos > -1) {
            startPos = tmp.indexOf("=", startPos);
            endPos = tmp.indexOf("&", startPos);
            if (endPos == -1)
                tmp = tmp.substring(0, startPos + 1) + value;
            else
                tmp = tmp.substring(0, startPos + 1) + value + tmp.substring(endPos);
        }
        else {
            if (tmp.length > 0 && tmp.indexOf("?", 0) > 0)
                tmp = tmp + "&";
            else
                tmp = "?";
            tmp = tmp + key + "=" + value;
        }
    }

    return tmp;
}


/*
Extract the base url up to the sign '?' from a url
*/
function extractBaseURL(url) {
    return url.split("?")[0];
}


/*
Extracts a query string from a url. The part after the sign '?'.
*/
function extractQueryString(url) {
    var qs = new String(url.split("?")[1]);
    if (qs.length > 0) qs = "?" + qs;
    return qs;
}

