﻿/******************************************
General application wide javascript scripts
******************************************/
function stringIsNullOrEmpty(text) {
    return (text == null || text.length == 0);
}

function subMenu(subMenuName, displayStatus)
{
    obj = window.document.getElementById(subMenuName);
    if (obj != null)
        obj.style.display = displayStatus;
}

function isUserAgent(distinctUserAgentNameSubstring)
{
    return (navigator.userAgent.toLowerCase().indexOf(distinctUserAgentNameSubstring.toLowerCase()) != -1);
}

function relayClick(targetButtonId) {
    var target = window.document.getElementById(targetButtonId);
    
    if (target == null)
        return;
    
    try
    {
        if (target.onclick != null)
            target.click();
        else if (target.href != null) {
            window.location = target.href;
        }
    }
    catch(rrr)
    {
        try {
            if (target.onclick != null && !/javascript/g.test(target.href) )
                target.onclick(null);
            else if (target.href != null)
                window.location = target.href;
        }
        catch (rrr) {
            //ugly fix
            if (target.href != null)
                window.location = target.href;
        }
    }
}

function pressReturnKeyEventHandler(eventObj, targetToClickObjectName) {
    
    var keyCode = 0;
    if (window.event)    // IE
        keyCode = eventObj.keyCode;
    else if (eventObj.which)    // Netscape/Firefox/Opera
        keyCode = eventObj.which;
    
    if (keyCode == 13) {
        
        if (!eventObj)
            eventObj = window.event;
        eventObj.cancelBubble = true;
        if (eventObj.stopPropagation)
            eventObj.stopPropagation();

        eventObj.returnValue = false;

        var target = window.document.getElementById(targetToClickObjectName);
        target.focus();
        if (target.onclick != null)
            target.click();
        else if (target.href != null)
            window.location = target.href;

        //eventObj.cancelBubble = true;

        return false;
    }

    return true;
}

function scrollToTop() {
    window.scroll(0, 300);
    window.scrollTo(0, 300);
}

// direction: 0 - first window, 1 - next window, (-1) - previous window
function showFilters(direction, windowSizeElementName, filterHitsCountElementName, currentWindowElementName, filtersContainerElementName, filterHitsInfoElementName)
{
    var windowSizeElement = window.document.getElementById(windowSizeElementName);
    var filterHitsCountElement = window.document.getElementById(filterHitsCountElementName);
    var currentWindowElement = window.document.getElementById(currentWindowElementName);

    // determine virtual windows parameters
    if (direction == 0) {
        currentWindowElement.value = "0";
    } else {
        var totalWindows = parseInt(filterHitsCountElement.value) / parseInt(windowSizeElement.value);
        if (Math.floor(totalWindows) < totalWindows)    // partially filled window
            totalWindows = Math.floor(totalWindows) + 1;
        
        // index of window to display
        var currentWindowIndex = parseInt(currentWindowElement.value) + direction;
        
        // looping mechanism
        if (currentWindowIndex < 0)
            currentWindowIndex = totalWindows - 1;
        else if (currentWindowIndex > totalWindows - 1)
            currentWindowIndex = 0;
        
        currentWindowElement.value = currentWindowIndex;
    }

    // convert from virtual windows to item indeces
    var firstFilterIndexToShow = parseInt(currentWindowElement.value) * parseInt(windowSizeElement.value) ;
    var lastFilterIndexToShow = Math.min((parseInt(currentWindowElement.value) + 1) * parseInt(windowSizeElement.value) - 1, parseInt(filterHitsCountElement.value) - 1);
    
    // do the actual showing
    var filterHitsInfoElement = window.document.getElementById(filterHitsInfoElementName);
    filterHitsInfoElement.innerHTML = (firstFilterIndexToShow + 1) + "-" + (lastFilterIndexToShow + 1) + "/" + filterHitsCountElement.value;

    var filtersContainerElement = window.document.getElementById(filtersContainerElementName);
    var filterElements = new Array();
    
    var i = 0;
    var j = 0;
    while (i < filtersContainerElement.childNodes.length) {
        if (filtersContainerElement.childNodes[i].nodeName.toLowerCase() == "li" && filtersContainerElement.childNodes[i].className == "") {
            filterElements[j] = filtersContainerElement.childNodes[i];
            j++;
        }
        i++;
    }
    
    for (i = 0; i < filterElements.length; i++) {
        if (firstFilterIndexToShow <= i && i <= lastFilterIndexToShow)
            filterElements[i].style.display = "";
        else
            filterElements[i].style.display = "none";
    }
}

function setDisplayStyleFor(arrayOfElementNames, displayStyle)
{
    for (i = 0; i < arrayOfElementNames.length; i++) {
        var element = window.document.getElementById(arrayOfElementNames[i]);
        if (element != null)
            element.style.display = displayStyle;
    }
}

function biziSearch(inputTextElementName) {
    var url = "http://www.bizi.si/bannersearch.aspx?tis=" + document.getElementById(inputTextElementName).value;
    var newWindow = window.open(url, 'bizi');
    newWindow.focus();
}

// needed for fckeditor
function FCKUpdateLinkedField(id) {
    try {
        if (typeof (FCKeditorAPI) == "object")
            FCKeditorAPI.GetInstance(id).UpdateLinkedField();
    } catch (err) {
    }
}

function openBanners() {
    window.open("AllBanners.aspx"/*"http://adserver.iprom.net/adserver/tisAllBanners.pl"*/, "Seznam_bannerjev", 'scrollbars=yes,toolbar=no,location=no,status=on,width=764,height=600');
}

function windowBackOrClose() {
    if (window.name == "mapprint")
        window.close();
    else
        window.history.back();
}

function shouldPublicationPrint(publicationObject, should) {
    while (publicationObject.parentNode != null && publicationObject.className.indexOf("publication") == -1)
        publicationObject = publicationObject.parentNode;

    if (isUserAgent("MSIE"))
        publicationObject.style.filter = "alpha(opacity=" + ((should) ? "100" : "40") + ")";
    else
        publicationObject.style.opacity = ((should) ? "1" : "0.4");

    publicationObject.className = ((should) ? "publication" : "publication noprint");
}

// execute the click of the button with provided id
function virtualSubmit(clientButtonID) {
    var btn = document.getElementById(clientButtonID);
    btn.click();
}

function bookmarkSite(title, url) {
    if (document.all) { // ie
        window.external.AddFavorite(url, title);
    } else if (window.sidebar) { // firefox
        window.sidebar.addPanel(title, url, "");
    } else if (window.opera && window.print) { // opera
        var elem = document.createElement("a");
        elem.setAttribute("href", url);
        elem.setAttribute("title", title);
        elem.setAttribute("rel", "sidebar");
        elem.click(); // this.title=document.title;
    }
}
// General application wide javascript scripts - end


/***********
ToolBoxState
***********/
function ToolBoxState() {
}

ToolBoxState.Mark = function(checkBoxElement, bagItemId, globalToolBoxItemsBagElementName, divResultItemId) {
    var globalToolBoxItemsBagElement = window.document.getElementById(globalToolBoxItemsBagElementName);
    var divResultItem = window.document.getElementById(divResultItemId);
    
    globalToolBoxItemsBagElement.value = globalToolBoxItemsBagElement.value.replace(bagItemId, "");

    if (checkBoxElement.checked)
        globalToolBoxItemsBagElement.value += bagItemId;

    if (divResultItem != null) {
        divResultItem.className = divResultItem.className.replace(" checked", "");

        if (checkBoxElement.checked)
            divResultItem.className += " checked";
    }
}

ToolBoxState.MarkAll = function(action, globalToolBoxItemsBagElementName, globalToolBoxCandidateItemsBagElementName, elementToShowName, elementToHideName) {
    // globalToolBoxItemsBagElementName and globalToolBoxCandidateItemsBagElementName required
    if (globalToolBoxItemsBagElementName == null || globalToolBoxCandidateItemsBagElementName == null)
        return;

    // if no candidates in hidden field then no action
    var globalToolBoxCandidateItemsBagElement = window.document.getElementById(globalToolBoxCandidateItemsBagElementName);
    if (globalToolBoxCandidateItemsBagElement.Value == "")
        return;

    var elementToShow = window.document.getElementById(elementToShowName);
    var elementToHide = window.document.getElementById(elementToHideName);

    var checkboxes = globalToolBoxCandidateItemsBagElement.value.replace(new RegExp("::", "g"), ",").replace(new RegExp(":", "g"), "").split(",");

    if (action == "check")
    {
        for (i = 0; i < checkboxes.length; i++)
        {
            var cbIdPair = checkboxes[i].split("/");    // [0] - checkbox element id, [1] - corresponding publication id
            var divResultItemId = cbIdPair[0].replace("cbResultItem_", "divResultItem_");
            var checkbox = window.document.getElementById(cbIdPair[0]);
            checkbox.checked = true;
            ToolBoxState.Mark(checkbox, ":" + cbIdPair[1] + ":", globalToolBoxItemsBagElementName, divResultItemId);
        }
    }
    else if (action == "uncheck")
    {
        for (i = 0; i < checkboxes.length; i++)
        {
            var cbIdPair = checkboxes[i].split("/");    // [0] - checkbox element id, [1] - corresponding publication id
            var divResultItemId = cbIdPair[0].replace("cbResultItem_", "divResultItem_");
            var checkbox = window.document.getElementById(cbIdPair[0]);
            checkbox.checked = false;
            ToolBoxState.Mark(checkbox, ":" + cbIdPair[1] + ":", globalToolBoxItemsBagElementName, divResultItemId);
        }
    }

    // toggle buttons visibility
    elementToShow.style.display = "";
    elementToHide.style.display = "none";
}
// ToolBoxState - end


/*********
news strip
*********/
var displayNews = 0;
var cycleNewsTimer = null;

function ShowText(buttonIndex)
{
	var textArray = new Array();
	
	for (i = 0; i < 10; i++)
	{
	    var id = "ctl00_TopLeftTop_NewsStrip1_RepeaterNews_ctl0" + i + "_text";
	    var obj = document.getElementById(id);
	    if (obj)
	        textArray.push(obj);
	    else
	        break;
	}

	for (var i = 0; i < textArray.length; i++)
	{
		textArray[i].style.display = "none";
    }

    textArray[buttonIndex].style.display = "block";
    
    if (cycleNewsTimer != null) {
        clearTimeout(cycleNewsTimer);
        displayNews = buttonIndex;
        cycleNewsTimer = setTimeout("CycleNews();", 30000);
    }
}

function CycleNews() {
    var textArray = new Array();

    for (i = 0; i < 10; i++) {
        var id = "ctl00_TopLeftTop_NewsStrip1_RepeaterNews_ctl0" + i + "_text";
        var obj = document.getElementById(id);
        if (obj)
            textArray.push(obj);
        else
            break;
    }

    if (textArray.length == 0)
        return;

    for (var i = 0; i < textArray.length; i++) {
        textArray[i].style.display = (i == displayNews) ? "block" : "none";
    }

    displayNews = (displayNews >= textArray.length - 1) ? 0 : displayNews + 1;
    cycleNewsTimer = setTimeout("CycleNews();", 30000);
}
// news stip - end


/******************
news strip advanced
******************/
var displayNewsGroup = 0;
var cycleNewsAdvancedTimer = null;
var listOfNewsGroupsAndButtons = null;

function ShowNewsTextAdvanced(buttonIndex) {
    // hide & deselect
    for (i = 0; i < listOfNewsGroupsAndButtons.length; i++) {
        listOfNewsGroupsAndButtons[i].group.style.display = "none";
        listOfNewsGroupsAndButtons[i].button.className = "";
    }

    // show & select
    listOfNewsGroupsAndButtons[buttonIndex].group.style.display = "block";
    listOfNewsGroupsAndButtons[buttonIndex].button.className = "sel";

    if (cycleNewsAdvancedTimer != null) {
        clearTimeout(cycleNewsAdvancedTimer);
        displayNewsGroup = buttonIndex;
        cycleNewsAdvancedTimer = setTimeout("CycleNewsAdvanced();", 5000);
    }
}

function getElementsByClassName(node, classname) {
    var a = [];
    var re = new RegExp('(^| )' + classname + '( |$)');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++)
        if (re.test(els[i].className)) a.push(els[i]);
    return a;
}

function CycleNewsAdvanced() {
    // init
    if (cycleNewsAdvancedTimer == null && listOfNewsGroupsAndButtons == null) {
        listOfNewsGroupsAndButtons = new Array();

        //var listOfGroups = window.document.getElementsByClassName("pagerGroup");
        //var listOfButtons = window.document.getElementsByClassName("newsPager")[0].getElementsByTagName("li");
        var listOfGroups = getElementsByClassName(document.body, "pagerGroup");
        var listOfButtons = getElementsByClassName(document.body, "newsPager")[0].getElementsByTagName("li");
        if (listOfGroups.length == listOfButtons.length) {   // must be true if everything ok
            for (var i = 0; i < listOfGroups.length; i++)
                listOfNewsGroupsAndButtons.push({ group: listOfGroups[i], button: listOfButtons[i] });
        }
    }

    if (listOfNewsGroupsAndButtons.length == 0)
        return;

    // show / hide & select / deselect
    for (var i = 0; i < listOfNewsGroupsAndButtons.length; i++) {
        if (i == displayNewsGroup) {
            listOfNewsGroupsAndButtons[i].group.style.display = "block";
            listOfNewsGroupsAndButtons[i].button.className = "sel";
            
            // asynchronous XMLHttpRequest
            recordStatistics("SPB", "SHOWN", "ITEM=" + i);
        } else {
            listOfNewsGroupsAndButtons[i].group.style.display = "none";
            listOfNewsGroupsAndButtons[i].button.className = "";
        }
    }

    displayNewsGroup = (displayNewsGroup >= (listOfNewsGroupsAndButtons.length - 1)) ? 0 : (displayNewsGroup + 1);
    cycleNewsAdvancedTimer = setTimeout("CycleNewsAdvanced();", 5000);
}
// news strip advanced - end


/*******
WebSites
*******/
function WebSites() {
}
WebSites.sitesContainer = null;
WebSites.totalSites = 0;
WebSites.timer = null;

WebSites.show = function(itemIndex) {
    var sites = WebSites.sitesContainer.getElementsByTagName("li");
    for (var i = 0; i < sites.length; i++) {
        sites[i].className = (i == itemIndex ? "sel" : "");
    }

    if (WebSites.timer != null)
        clearTimeout(WebSites.timer);
    
    nextSite = (itemIndex + 1) % WebSites.totalSites;
    WebSites.timer = setTimeout("WebSites.show(" + nextSite + ");", 5000);
}
// WebSites - end


/***************
XMLHttpRequester
***************/
// constants
var XMLHttpFactories = [
    function() { return new XMLHttpRequest() },
    function() { return new ActiveXObject("Msxml2.XMLHTTP") },
    function() { return new ActiveXObject("Msxml3.XMLHTTP") },
    function() { return new ActiveXObject("Microsoft.XMLHTTP") } ];

// constructor
function XMLHttpRequester() {
    this.xmlHttpReq = false;
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            this.xmlHttpReq = XMLHttpFactories[i]();
        } catch (e) {
            continue;
        }
        break;
    }

    return this;
}

// methods
XMLHttpRequester.prototype = {
    /*
    * url - send request to this url
    * callback - function that will handle response
    * postData - optional "GET" (default) or "POST" method
    */
    sendRequest: function(url, callback, postData) {
        if (!this.xmlHttpReq)
            return;

        var method = (postData) ? "POST" : "GET";

        var selfRef = this.xmlHttpReq;
        selfRef.open(method, url, true);
        //selfRef.setRequestHeader('User-Agent', 'XMLHTTP/1.0');

        if (postData)
            selfRef.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        selfRef.onreadystatechange = function() {
            if (selfRef.readyState != 4)
                return;
            if (selfRef.status != 200 && selfRef.status != 304) {
                //alert('HTTP error ' + selfRef.status);
                return;
            }

            callback(selfRef);
        }

        if (selfRef.readyState == 4)
            return;

        selfRef.send(postData);
    }
}
// XMLHttpRequester - end


/*********
Statistics
*********/
/*
* forType - unique name that will be recognized and processed by server
* eventName - "SHOWN", "CLICKED", ...
* parameters - optional query-string like additional parameters (e.g. "ID=123&APPNAME=itis&...")
*/
function dummyCallbackHandler(request) {
    return;
}

function recordStatistics(forType, eventName, parameters) {
    if (parameters != null && parameters.length > 0)
        parameters = "&" + parameters;
    else
        parameters = "";
    var date = new Date();
    (new XMLHttpRequester()).sendRequest("StatsUpdate.aspx?TYPE=" + forType + "&EVENT=" + eventName + parameters + "&RND=" + date.getTime() + date.getMilliseconds(), dummyCallbackHandler);
}
// Statistics - end


/****
MyTIS
****/
function MyTIS() {
}

MyTIS.showAllNumbers = function(itemDivId) {
    var itemDiv = window.document.getElementById(itemDivId);
    itemDiv.className = itemDiv.className.replace("conClosed", "conOpened");
}

MyTIS.toggleImportExport = function(divToShowId, divToHideId) {
    window.document.getElementById(divToShowId).style.display = "block";
    window.document.getElementById(divToHideId).style.display = "none";
}
// MyTIS - end


/************
ResultsFilter
************/
function ResultsFilter() {
}

// override when using filters
ResultsFilter.MessageFieldId = null;
ResultsFilter.ApplyButtonId = null;
ResultsFilter.RemoveButtonId = null;
ResultsFilter.CustomButtonId = null;

ResultsFilter.apply = function(filterName, itemName) {
    window.document.getElementById(ResultsFilter.MessageFieldId).value = filterName + ":" + itemName;
    relayClick(ResultsFilter.ApplyButtonId);
}

ResultsFilter.remove = function(filterName, itemName) {
    window.document.getElementById(ResultsFilter.MessageFieldId).value = filterName + ":" + itemName;
    relayClick(ResultsFilter.RemoveButtonId);
}

ResultsFilter.custom = function(args) {
    window.document.getElementById(ResultsFilter.MessageFieldId).value = args;
    relayClick(ResultsFilter.CustomButtonId);
}

ResultsFilter.toggleOptions = function(filterSequenceNumber) {
    var filter = window.document.getElementById("Filter_" + filterSequenceNumber);
    var allFilters = filter.parentNode.getElementsByTagName("LI");
    var filterOptions = window.document.getElementById("FilterOptions_" + filterSequenceNumber);
    var allFiltersOptions = new Array();
    var t = filterOptions.parentNode.getElementsByTagName("DIV");
    var i;
    for (i = 0; i < t.length; i++) {
        if (t[i].className.indexOf("filterTab") != -1)
            allFiltersOptions.push(t[i]);
    }

    var hide = (filter.className == "sel");

    for (i = 0; i < allFilters.length; i++) {
        allFilters[i].className = "";
        allFiltersOptions[i].style.display = "none";
    }

    if (!hide) {
        filter.className = "sel";
        filterOptions.style.display = "block";
    }
}

ResultsFilter.showPage = function(filterSequenceNumber, pageIndex) {
    var page = window.document.getElementById("ResultsFilterPage_" + filterSequenceNumber + "_" + pageIndex);
    var allPages = page.parentNode.getElementsByTagName("UL");
    var pagerLink = window.document.getElementById("FilterPager_" + filterSequenceNumber + "_" + pageIndex);
    var allPagerLinks = pagerLink.parentNode.parentNode.getElementsByTagName("A");

    for (var i = 0; i < allPages.length; i++) {
        allPages[i].style.display = "none";
        allPagerLinks[i].className = "";
    }

    page.style.display = "block";
    pagerLink.className = "sel";
}
// ResultsFilter - end


/********
ResultsAd
********/
function ResultsAd() {
}

ResultsAd.timer = null;

ResultsAd.show = function(adContainerId) {
    var adContainer = window.document.getElementById(adContainerId);
    adContainer.className = adContainer.className.replace(" add-mod-open", "") + " add-mod-open";
}

ResultsAd.showDelayed = function(adContainerId) {
    if (ResultsAd.timer != null)
        clearTimeout(ResultsAd.timer);

    ResultsAd.timer = setTimeout("ResultsAd.show('" + adContainerId + "');", 500);
}

ResultsAd.hide = function(adContainerId) {
    if (ResultsAd.timer != null)
        clearTimeout(ResultsAd.timer);
        
    var adContainer = window.document.getElementById(adContainerId);
    adContainer.className = adContainer.className.replace(" add-mod-open", "");
}

ResultsAd.toggle = function(adContainerId) {
    var adContainer = window.document.getElementById(adContainerId);
    if (adContainer.className.indexOf(" add-mod-open") > 0)
        ResultsAd.hide(adContainerId);
    else
        ResultsAd.show(adContainerId);
}
// ResultsAd - end

