// klipove
// 130x95
// 100x70
// 80x55
// kartinki
// 130x120

if (typeof tpl_image_url == 'undefined') {
    var tpl_image_url = "./templates/HDBox/images";
}

function initRoundedCorners1px(context) {
    if (typeof context == 'undefined') context= document.body;
    var brd_types = new Array('tdborder', 'iborder', 'cborder');
    for (var i=0; i<brd_types.length; i++) {
        $("table.tablehead > tbody > tr > td."+brd_types[i], context).each(function() {
            var w = getCSSValue(this, "border-left-width");
            if (w > 0) {
                var c = getCSSColor(this, "borderColor", "border-left-color");
                var img = "<img src='" + tpl_image_url + "/spacer.gif' width='"+w+"' height='"+w+"'>";
                var td = "<td width='"+w+"' style='background-color:" + c + ";'>" + img + "</td>"
                var tr = "<tr><td width='"+w+"' height='"+w+"'>" + img + "</td><td style='background-color:" + c + ";'></td><td width='"+w+"'></td></tr>";
                $(this).css("border", "none").before(td).after(td);
                $(this.parentNode).before(tr).after(tr);
            }
        });
    }
}

function initChannelButtonHover() {
    $(".channel_button,.share_button")
    .mouseover(function() { if (empty(this.back_pos_x)) this.back_pos_x = getCSSValue(this, "background-position-x"); setCSSValue(this, "background-position-x", this.back_pos_x - 18); })
    .mouseout(function() { if (empty(this.back_pos_x)) this.back_pos_x = getCSSValue(this, "background-position-x"); setCSSValue(this, "background-position-x", this.back_pos_x); })
}

onLoadExec(initRoundedCorners1px, 200);
onLoadExec(initChannelButtonHover, 1000);

onLoadExec(function() {
    animateButton(".cont-button-table", "cont-button-table");
    initHints();
    initAjaxComments();
});


function getDestId() {
    var m= window.location.href.match(/(clip_id|image_id|pano_id|id)=(\d*)/);
    if (!m) var m= window.location.href.match(/[a-z0-9\.\-]+\/([^\/\.]+)\/([0-9]+)/);
    return m[2];
}


function getFeederType() {
    var m= window.location.href.match(/\/([^\/]*?)\.php/);
    if (!m) var m= window.location.href.match(/\/([^\/\.]+)\//);
    if (!m) return "index";
    return m[1];
}


function initHints() {
    return; // hints not used - use overlib

    hideDiv("channelItemHintContainer");

    $(".channel-item-hint").hover(
        function(e) {
            if (Browser.moz) {
                var screen_width = window.innerWidth;
                var screen_height = window.innerHeight;
            } else {
                var screen_width = document.body.clientWidth;
                var screen_height = document.body.clientHeight;
            }

            offset = $(this).offset();
            hintContainer = $($(this).next());
            w = $("#channelItemHintContainer").width();
            l = offset.left + ((offset.left + $(this).width() + w <= screen_width) ? $(this).width() + 2 : - w - 12);

            $("#channelItemHintContainer")
                .html(hintContainer.html())
                .css({
                    "top": offset.top + "px",
                    "left": l + "px",
                    "width": w + "px"
                })
                .css("display", "block");
        },
        function(e) { $("#channelItemHintContainer").css("display", "none"); }
    );
}


function initAjaxComments() {
    $("#comments-div .paging a").click(function(e) {
        e.preventDefault();
        loadComments($(this).attr("href").match(/page=(\d*)/)[1]);
    });
}


function loadComments(page) {
    feederURL = aparg(tpl_feeder, "mode=comments&type=" + getFeederType() +
        "&dest_id=" + getDestId() +
        "&fmt=inner" +
        "&page=" + page +
        "&comment_level=" + comment_level +
        "&cl=" + comment_level);
    window.location.href= window.location.href.replace(/#.*/, "") + "#comments";
    ahahLoad(getEl("comments-div"), feederURL, function() {
        onLoad_init();
        initRoundedCorners1px(getEl("comments-div"));
        initAjaxComments();
        }, 1, 1);
}


function getFirstChild(node) {
    var firstChild = node.firstChild;
    while (firstChild != null && firstChild.nodeType === 3) {
        firstChild = firstChild.nextSibling;
    }
    return firstChild;
}



function updateContActions(src_button, dest_pane_id) {
    var changes = 0;
    $("#ctrl_actions > td > table > tbody > tr").each(function() {
        if (this == getEl(dest_pane_id)) {
            if ($(this).css("display") != "none") {
                $(this).css("display", "none");
            } else {
                $(this).css("display", "");
                changes++;
            }
        } else {
            $(this).css("display", "none");
        }
    });

    if (!changes) {
        $("#ctrl_actions").css("display", "none");
    } else {
        $("#ctrl_actions").css("display", "");
    }
}


//////////// page state
function saveState() {
    createCookie(
        "_state",
        Number($("#similar-conts-link").hasClass("foldable-table-expanded")) * 1 +
        Number($("#similar-conts-list").hasClass("radio-on")) * 2 +

        Number($("#more-user-cont-link").hasClass("foldable-table-expanded")) * 4 +
        Number($("#more-user-cont-list").hasClass("radio-on")) * 8 +

        Number($("#daily-cont-link").hasClass("foldable-table-expanded")) * 16 +
        Number($("#daily-cont-list").hasClass("radio-on")) * 32 +

        Number($("#random-cont-link").hasClass("foldable-table-expanded")) * 64 +
        Number($("#random-cont-list").hasClass("radio-on")) * 128 +

        Number($("#cont-info-foldable-link").hasClass("foldable-table-expanded")) * 2048 +
        Number($("#cont-info-user-foldable-link").hasClass("foldable-table-expanded")) * 4096 +

        Number($("#tags-link").hasClass("foldable-table-expanded")) * 8192,
        Number($("#adds-link").hasClass("foldable-table-expanded")) * 16384,
        100);
}




/**
*** Google maps popup
**/
var opened_maps = new Array();

function show_google_maps(lat_input, lng_input, location_name) {
    var rnd = Math.random() + "";
    var cnt = opened_maps.length;
    opened_maps[rnd] = new Array(2);
    opened_maps[rnd][0] = lat_input;
    opened_maps[rnd][1] = lng_input;
    opened_maps[rnd][2] = location_name;
    window_open(aparg(tpl_feeder, "mode=googlemaps&random="+rnd), 640, 480, "Double click to select new location or drag the current one");
}

function get_lat_lng(map_url) {
    map_url = map_url.match(/random=([.\d]*)/);
    if (map_url && typeof opened_maps[map_url[1]] != 'undefined') {
        return [opened_maps[map_url[1]][0].value, opened_maps[map_url[1]][1].value, opened_maps[map_url[1]][2].value];
    } else {
        return [0, 0, ""];
    }
}

function set_lat_lng(map_url, lat, lng) {
    map_url = map_url.match(/random=([.\d]*)/);
    if (map_url && typeof opened_maps[map_url[1]] != 'undefined') {
        opened_maps[map_url[1]][0].value = lat;
        opened_maps[map_url[1]][1].value = lng;
    }
}


/**
*** Static maps popup
**/
var opened_static_maps = new Array();

function show_vtour_map(vtour_id, x_input, y_input, location_name) {
    var rnd = Math.random() + "";
    var cnt = opened_static_maps.length;
    opened_static_maps[rnd] = new Array(2);
    opened_static_maps[rnd][0] = x_input;
    opened_static_maps[rnd][1] = y_input;
    opened_static_maps[rnd][2] = location_name;
    window_open(aparg(tpl_feeder, "mode=staticmaps&random="+rnd), 640, 480, "Double click to select new location or drag the current one");
}

function get_x_y(map_url) {
    map_url = map_url.match(/random=([.\d]*)/);
    if (map_url && typeof opened_static_maps[map_url[1]] != 'undefined') {
        return [opened_static_maps[map_url[1]][0].value, opened_static_maps[map_url[1]][1].value];
    } else {
        return [0, 0];
    }
}

function set_x_y(map_url, x, y) {
    map_url = map_url.match(/random=([.\d]*)/);
    if (map_url && typeof opened_static_maps[map_url[1]] != 'undefined') {
        opened_static_maps[map_url[1]][0].value = x;
        opened_static_maps[map_url[1]][1].value = y;
    }
}


/**
*** background iframe jquery plugin - defeat ie6 z-index bug
**/
(function($){
    $.fn.bgIframe = $.fn.bgiframe = function(s) { // This is only for IE6
      if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
        s = $.extend({
          top : 'auto', // auto == .currentStyle.borderTopWidth
          left : 'auto', // auto == .currentStyle.borderLeftWidth
          width : 'auto', // auto == offsetWidth
          height : 'auto', // auto == offsetHeight
          opacity : true,
          src : 'javascript:false;'
        }, s || {});
        var prop = function(n) { return n && n.constructor == Number ? n+'px' : n; },
         html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
         'style="display:block;position:absolute;z-index:-1;'+
           (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
               'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
               'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
               'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
               'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
              '"/>';
        return this.each(function() {
          if ($('> iframe.bgiframe', this).length == 0) this.insertBefore( document.createElement(html), this.firstChild );
        });
      }
      return this;
    };
})(jQuery);


/**
***  Foldables
**/
var globalFoldablesStateMask = 1;
var globalFoldablesExistStateMask = 0;
var hiddenFoldablesCount = 0;
var foldables = [];

var lang_fold_closed_panel = "There is 1 closed panel on this page";
var lang_fold_closed_panels = "There are %count closed panels on this page";
var lang_fold_close_confirm = "Do you want to close this panel? You can restore closed panels from the box in the lower right corner.";

function initFoldable(link, listLink, boxLink, feederParams, beforeRequestCallback, showWaitIndicator, stateMask, moreText, lessText) {
    link = getEl(link);
    if (!link) {
        debug("foldable not found and therefore not initalized!");
        return;
    };
    link.listLink = getEl(listLink);
    link.boxLink = getEl(boxLink);
    link.targetContainer = getEl(link.hash.substr(1));
    link.hidden = false;
    link.feederParams = feederParams;
    link.beforeRequestCallback = beforeRequestCallback;
    link.showWaitIndicator = showWaitIndicator;
    link.moreText = empty(moreText) ? "&raquo; more" : moreText;
    link.lessText = empty(lessText) ? "&laquo; less" : lessText;
    if (stateMask) {
        link.stateMask = stateMask;
    } else {
        link.stateMask = globalFoldablesStateMask;
        globalFoldablesStateMask <<= 1;
    };
    globalFoldablesExistStateMask |= link.stateMask;

    var prnt = link.parentNode;
    while (prnt && !hasClass(prnt, "fold_container")) {
        prnt = prnt.parentNode;
    };
    if (!prnt) {
        debug(link.id+' has no parent. no foldable mode');
        return;
    };
    link.foldable = prnt;
    foldables.push(link);
    restoreFoldableState(link);

    link.onclick = function(e) {
        if (isVisible(this.targetContainer)) {
            var img = getFirstChild(this);
            if (empty(img)) {
                this.innerHTML = this.moreText;
            } else {
                removeClass(img, "fold_expanded");
                addClass(img, "fold");
            };
            hideDiv(this.targetContainer);
        } else {
            var img = getFirstChild(this);
            if (empty(img)) {
                this.innerHTML = this.lessText;
            } else {
                removeClass(img, "fold");
                addClass(img, "fold_expanded");
            };
            showDiv(this.targetContainer);
            loadFoldable(this);
        };
        saveFoldableState(this);
        return false;
    };

    if (listLink) {
        getEl(listLink).onclick = function(e) {
            if (link.feederParams["ltype"] && link.feederParams["ltype"] != "list") {
                link.feederParams["ltype"] = "list";
                if (isVisible(link.targetContainer)) loadFoldable(link);
                saveFoldableState(link);
                toggleRadio(this);
            };
            return false;
        };
    };

    if (boxLink) {
        getEl(boxLink).onclick = function(e) {
            if (link.feederParams["ltype"] && link.feederParams["ltype"] != "box") {
                link.feederParams["ltype"] = "box";
                if (isVisible(link.targetContainer)) loadFoldable(link);
                saveFoldableState(link);
                toggleRadio(this);
            };
            return false;
        };
    };
}

function toggleRadio(radio) {
    var radios = radio.parentNode.childNodes;
    for (var i = 0; i < radios.length; i++) {
        var currentRadio = radios[i].childNodes[0];
        var hasBoxRadio = hasClass(currentRadio, "box_radio");
        var hasBoxRadioOn = hasClass(currentRadio, "box_radio_on");
        var hasListRadio = hasClass(currentRadio, "list_radio");
        var hasListRadioOn = hasClass(currentRadio, "list_radio_on");
        if (hasBoxRadio || hasBoxRadioOn) {
            removeClass(currentRadio, (hasBoxRadio ? "box_radio" : "box_radio_on"));
            addClass(currentRadio, (hasBoxRadio ? "box_radio_on" : "box_radio"));
        } else {
            removeClass(currentRadio, (hasListRadio ? "list_radio" : "list_radio_on"));
            addClass(currentRadio, (hasListRadio ? "list_radio_on" : "list_radio"));
        }
    }
}

function saveFoldableState(foldable) {
    var cookieSuffix = getFeederType();

    createCookie("e_" + cookieSuffix, globalFoldablesExistStateMask, 100);

    var f_state = readCookie("f_" + cookieSuffix);
    if (!f_state) f_state = 0;
    if (foldable.targetContainer.style && (foldable.targetContainer.style.display != 'none')) {
        f_state |= foldable.stateMask;
    } else {
        f_state &= ~foldable.stateMask;
    }
    createCookie("f_" + cookieSuffix, f_state, 100);

    var r_state = readCookie("r_" + cookieSuffix);
    if (!r_state) r_state = 0;
    if ((foldable.feederParams && foldable.feederParams["ltype"] && foldable.feederParams["ltype"] == "list")) {
        r_state |= foldable.stateMask;
    } else {
        r_state &= ~foldable.stateMask;
    }
    createCookie("r_" + cookieSuffix, r_state, 100);

    if (hasClass(foldable.foldable, "fold_container")) {
        var h_state = readCookie("h_" + cookieSuffix);
        if (!h_state) h_state = 0;
        if (!isVisible(foldable.foldable)) {
            h_state |= foldable.stateMask;
        } else {
            h_state &= ~foldable.stateMask;
        }
        createCookie("h_" + cookieSuffix, h_state, 100);
    }
}

function saveAllFoldablesState() {
    for (var i = 0; i < foldables.length; i++) {
        saveFoldableState(foldables[i]);
    }
}

function restoreFoldableState(foldable) {
    var cookieSuffix = getFeederType();
    var img = getFirstChild(foldable);

    var e_state = readCookie("e_" + cookieSuffix);

    var f_state = readCookie("f_" + cookieSuffix);
    if (e_state && (e_state & foldable.stateMask)) {
        if (f_state) {
            if (f_state & foldable.stateMask) {
                if (empty(img)) foldable.innerHTML = foldable.lessText;
                else {
                    removeClass(img, "fold");
                    addClass(img, "fold_expanded");
                }
                showDiv(foldable.targetContainer);
            } else {
                if (empty(img)) foldable.innerHTML = foldable.moreText;
                else {
                    removeClass(img, "fold_expanded");
                    addClass(img, "fold");
                }
                hideDiv(foldable.targetContainer);
            }
        }
    }

    var r_state = readCookie("r_" + cookieSuffix);
    if (r_state && foldable.feederParams && foldable.feederParams["ltype"]) {
        if (r_state & foldable.stateMask) {
            foldable.feederParams["ltype"] = "list";
            addClass(getFirstChild(foldable.listLink), "list_radio_on");
            removeClass(getFirstChild(foldable.listLink), "list_radio");
            addClass(getFirstChild(foldable.boxLink), "box_radio");
            removeClass(getFirstChild(foldable.boxLink), "box_radio_on");
        } else {
            foldable.feederParams["ltype"] = "box";
            addClass(getFirstChild(foldable.listLink), "list_radio");
            removeClass(getFirstChild(foldable.listLink), "list_radio_on");
            addClass(getFirstChild(foldable.boxLink), "box_radio_on");
            removeClass(getFirstChild(foldable.boxLink), "box_radio");
        }
    }

    if (hasClass(foldable.foldable, "fold_container")) {
        var h_state = readCookie("h_" + cookieSuffix);
        if (h_state & foldable.stateMask) {
            hideDiv(foldable.foldable);
            hiddenFoldablesCount++;
        } else {
            showDiv(foldable.foldable);
        }
    }

    if (isVisible(foldable.targetContainer)) {
        loadFoldable(foldable);
    }
}

function loadFoldable(foldable) {
    foldable = getEl(foldable);
    if (foldable.feederParams) {
        if (foldable.beforeRequestCallback) foldable.beforeRequestCallback(foldable);
        if (foldable.showWaitIndicator) getFirstChild(foldable.targetContainer).innerHTML = "<div class='channel-container'></div>";

        var feederURL = tpl_feeder;
        for (var param in foldable.feederParams) {
            feederURL = aparg(feederURL, param + "=" + foldable.feederParams[param]);
        }

        if (foldable.feederParams["ltype"] && (foldable.feederParams["ltype"] == "box")) {
            feederURL = aparg(feederURL, "tm=mini");
        }

        ahahLoad(getFirstChild(foldable.targetContainer), feederURL, function(response, status, statusText) {
            var targetStyle = getFirstChild(foldable.targetContainer).style;
            if (getFirstChild(getFirstChild(foldable.targetContainer))) {
                var targetDivStyle = getFirstChild(getFirstChild(foldable.targetContainer)).style;

                if (foldable.showWaitIndicator) targetDivStyle.backgroundImage = "url("+(!empty(tpl_image_url) ? tpl_image_url : "")+"/spacer.gif)";
                if (targetStyle.width) targetDivStyle.width = targetStyle.width;
                if (targetStyle.height) targetDivStyle.height = targetStyle.height;
            }

            initHints();
        }, 1, 1);
    }
}

function updateHiddenFoldablesInfo() {
    if (hiddenFoldablesCount == 0) {
        hideDiv("hidden_foldables");
    } else {
        if (hiddenFoldablesCount == 1) {
            getEl("hidden_foldables_text").innerHTML = lang_fold_closed_panel;
        } else {
            getEl("hidden_foldables_text").innerHTML = str_replace(lang_fold_closed_panels, "%count", hiddenFoldablesCount);
        }

        showDiv("hidden_foldables");
    }
}

function hideFoldable(foldable) {
    if (!confirm(lang_fold_close_confirm)) return;
    foldable = getEl(foldable);
    hideDiv(foldable.foldable);
    saveFoldableState(foldable);
    hiddenFoldablesCount++;
    updateHiddenFoldablesInfo();
}

function showAllFoldables() {
    hiddenFoldablesCount = 0;
    createCookie("h_" + getFeederType(), 0, 100);

    for (var i = 0; i < foldables.length; i++) {
        restoreFoldableState(foldables[i]);
    }

    updateHiddenFoldablesInfo();
}


/*
**  krpano
*/
function restoreKrpanoState() {
    krpano_loaded = true;

    if (typeof krp_edit_mode != "undefined") return;

    var state = readCookie("_krp");
    if (state) {
        if (state & 1) krpanoInstance.set("hotspot.visible", "false");

        if ((state & 2) && eval(krpanoInstance.get("action[show_map]"))) {
            krpanoInstance.call("action(show_map);");
            krpanoInstance.set("plugin[map].map_is_pinned", "true");
            krpanoInstance.call("action(show_pin_buttons);");
        }
    }
}

function saveKrpanoState() {
    var hotspots = eval(krpanoInstance.get("hotspot.visible"));
    var map_is_pinned = eval(krpanoInstance.get("plugin[map].map_is_pinned"));
    var state = (hotspots ? 0 : 1) | (map_is_pinned ? 2 : 0);
    createCookie("_krp", state, 100);
}