﻿/****************************
* GATracker.js
****************************/
/*
*  EventRegistrar - Advanced element's event registration helper class

Usage on page:
(include EventRegistrar class definition script bellow)
...
// create helper object
var _eventRegistrar = new EventRegistrar();

// define event handler using predefined event risers, event types and actions for event handler
function EventProcessor(event) {
var eventRiserElementId = null;

if (window.event == null) {
eventRiserElementId = event.target.id;
} else {
eventRiserElementId = window.event.srcElement.id;
}

if (eventRiserElementId == null) {
return;
}

for (i = 0; i < _eventRegistrar.EventLookupTable.length; i++) {
if (eventRiserElementId == _eventRegistrar.EventLookupTable[i][0]) {
// do something with predefined defined action
// e.g. alert(_eventRegistrar.EventLookupTable[i][2]);
// or eval(_eventRegistrar.EventLookupTable[i][2]);
}
}
}
...
// define event listeners for elements by id, their event types and actions for event handler
_eventRegistrar.EventLookupTable.push(['someButton', 'click', 'someFunctionCall(x, y, z);']);
_eventRegistrar.EventLookupTable.push(['someAnchor', 'mouseover', 'var x = 3; alert(x);']);
...
// bind defined event handler to helper object
_eventRegistrar.BindEventListeners(EventProcessor);
*/

// constructor
function EventRegistrar() {
    this.EventLookupTable = new Array();
}

// properties
EventRegistrar.EventLookupTable = null;

// methods
EventRegistrar.prototype = {
    AddEventListener: function(elementId, eventType, eventHandler) {
        var result = true;

        var element = window.document.getElementById(elementId);
        if (element == null)
            return false;

        if (element.addEventListener) {
            element.addEventListener(eventType, eventHandler, false);
        } else if (element.attachEvent) {
            result = element.attachEvent("on" + eventType, eventHandler);
        } else {
            element["on" + eventType] = eventHandler;
        }

        return result;
    },
    BindEventListeners: function(eventHandler) {
        for (i = 0; i < this.EventLookupTable.length; i++) {
            this.AddEventListener(this.EventLookupTable[i][0], this.EventLookupTable[i][1], eventHandler);
        }
    }
}
//  EventRegistrar - end

/****************************
* pis.js
****************************/

g_sLang = "SI";
var glbEncoding = true;

if (!theForm) {
    var theForm = document.forms['aspnetForm'];
    if (!theForm)
        theForm = document.aspnetForm;
}

function bookmarksite(title, url) {
    if (window.external)
        window.external.AddFavorite(url, title);
    else if (window.sidebar)
        window.sidebar.addPanel(title, url, "");
}

function checkEmail(email) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email))
        return true;

    return false;
}

function formatPrice(value) {
    var ret = Math.round(value * 100).toString();
    var len = ret.length;
    if (len == 1) {
        ret = "00" + ret;
        len = 3
    }
    if (len == 2) {
        ret = "0" + ret;
        len = 3
    }

    return (separateAboveThousand(ret.substring(0, len - 2)) + "," + ret.substring(len - 2, len));
}

function separateAboveThousand(intAsString) {
    if (intAsString.length < 4)
        return intAsString;

    var result = intAsString.substring(intAsString.length - 3, intAsString.length);
    for (i = intAsString.length - 4; i >= 0; i--) {
        if ((intAsString.length - 1 - i) % 3 == 0)
            result = "." + result;
        result = intAsString.charAt(i) + result;
    }

    return result;
}

function openMapTis(x, y, name) {
    var mapLink = encodeURI(encodeURI("http://www.itis.si/Page_Map.aspx?X=" + x + "&Y=" + y + "&n=" + name));
    var mapWindow = window.open(mapLink, "karta", "toolbar=no,location=no,status=yes,width=1024,height=768,resizable=yes,scrollbars=yes");
    mapWindow.focus();
}

function checkString(sStr, sAllow) {
    var nAllowLen = sAllow.length;
    var nLen = sStr.length;
    var nCnt = 0;
    var bIsChar = true;

    for (i = 0; i < nLen; i++) {
        ch = sStr.charAt(i);
        nCnt = 0;
        do {
            ch2 = sAllow.charAt(nCnt);
            nCnt++;
        } while ((nCnt < nAllowLen) && (ch != ch2));

        if (ch != ch2)
            bIsChar = false;
    }

    return bIsChar;
}

function GetInnerText(xStr) {
    var regExp = /<\/?[^>]+>/gim;
    xStr = xStr.replace(regExp, "");
    regExp = /\s\s/igm;
    xStr = xStr.replace(regExp, "");
    regExp = /^\s/gim;
    xStr = xStr.replace(regExp, "");

    return xStr;
}

//Hex to Dec converter
var hD = "0123456789ABCDEF";
function d2h(d) {
    var h = hD.substr(d & 15, 1);
    while (d > 15) {
        d >>= 4;
        h = hD.substr(d & 15, 1) + h;
    }
    return h;
}

function h2d(h) {
    return parseInt(h, 16);
}

function getCrc(input, crclen) {
    var lcrc = 0;
    for (var counter = 0; counter < input.length; counter++)
        lcrc += input.charCodeAt(counter);

    var hcrc = d2h(lcrc);
    var scrc = new String();
    for (var i = hcrc.length; i < crclen; i++)
        scrc += "0";
    scrc += hcrc;

    return scrc;
}

// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
    } while (i < input.length);

    return output;
}

function decode64(input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64)
            output = output + String.fromCharCode(chr2);
        if (enc4 != 64)
            output = output + String.fromCharCode(chr3);
    } while (i < input.length);

    return output;
}

function encrypt(input) {
    if (!glbEncoding)
        return input;
    input += getCrc(input, 8);

    var encrypted_string = ""

    var keyarray = new Array();
    keyarray[0] = 116;
    keyarray[1] = 0;
    keyarray[2] = 105;
    keyarray[3] = 0;
    keyarray[4] = 115;
    keyarray[5] = 0;

    var keycounter = 0;
    adnull = false;
    for (var counter = 0; counter < input.length; counter++) {
        // Get the current cookie character
        do {
            if (!adnull)
                icharacter = input.charCodeAt(counter) % 256;
            else
                icharacter = Math.floor(input.charCodeAt(counter) / 256);

            key_character = keyarray[keycounter];
            keycounter++;
            if (keycounter == keyarray.length)
                keycounter = 0;

            encChar = (icharacter ^ key_character) % 256;
            encrypted_string += String.fromCharCode(encChar);
            adnull = !adnull;
        }
        while (adnull);
    }

    return encode64(encrypted_string);
}

// Client key envent handlers
function SubmitSearchOnEnterPressed(clientSearchButtonControlId, clientEvent) {
    var keyCode;

    if (window.event)    // IE
        keyCode = clientEvent.keyCode;
    else if (clientEvent.which)    // Netscape/Firefox/Opera
        keyCode = clientEvent.which;

    if (keyCode == 13) {    // enter pressed?
        window.document.getElementById(clientSearchButtonControlId).click();
        clientEvent.cancelBubble = true;
        clientEvent.returnValue = false;
    }

    return true;
}

var helpWnd = null;
var helpUrl = null;
function openHelp() {
    if (!helpWnd)
        helpWnd = window.open(helpUrl, 'Pomoč', 'toolbar=no,location=no,scrollbars=1,status=yes,width=1000,height=640,resizable=1,resizable=yes');

    if (helpWnd) {
        try {
            helpWnd.focus();
        } catch (exc) {
            helpWnd = null;
            openHelp(); //do it again
        }
    }
}

function openHelp(hrefTag) {

    if (hrefTag == null)
        hrefTag = "";

    if (!helpWnd)
        helpWnd = window.open(helpUrl + '#' + hrefTag, 'Pomoč', 'toolbar=no,location=no,scrollbars=1,status=yes,width=800,height=600,resizable=1,resizable=yes');

    if (helpWnd) {
        try {
            helpWnd.focus();
        } catch (exc) {
            helpWnd = null;
            openHelp(hrefTag); //do it again
        }
    }
}

function ToggleExpansionAs(expandingElementId, displayValue) {
    var element = window.document.getElementById(expandingElementId);
    if (element == null)
        return;

    if (element.style.display == "none")
        element.style.display = displayValue;
    else
        element.style.display = "none";
}

function ToggleExpansion(expandingElementId) {
    var element = window.document.getElementById(expandingElementId);
    if (element == null)
        return;

    if (element.style.display == "none")
        element.style.display = "";
    else
        element.style.display = "none";
}

function ToggleHeadColor(headElementId, color1, color2) {
    var element = window.document.getElementById(headElementId);
    if (element == null)
        return;

    if (element.style.color.replace((new RegExp(" ", "g")), "") == color1)   // spacing in-sensitive check
        element.style.color = color2;
    else
        element.style.color = color1;
}

/* needed for fckeditor*/
function FCKUpdateLinkedField(id) {
    try {
        if (typeof (FCKeditorAPI) == "object")
            FCKeditorAPI.GetInstance(id).UpdateLinkedField();
    } catch (err) {
    }
}

function AddClickFunction(clientID) {
    var b = document.getElementById(clientID);
    if (b && typeof (b.click) == 'undefined') {
        b.click = function() {
            var result = true;
            if (b.onclick)
                result = b.onclick();
            if (typeof (result) == 'undefined' || result)
                eval(b.href);
        }
    }
}

function downloadFile(f) {
    win = window.open(f, '', 'toolbar=no,location=no,status=no,width=400,height=250,resize=no');
    if (win != null)
        win.focus();
}

function openBanners() {
    window.open("AllBanners.aspx", "Seznam_bannerjev", 'scrollbars=yes,toolbar=no,location=no,status=on,width=764,height=600');
}

function getSelectedOption(selectElementId) {
    var select = window.document.getElementById(selectElementId);

    if (select == null)
        return null;

    return select.options[select.selectedIndex];
}

/* This method resizes the iframe to match it's content */
function autoResize(id) {
    var newheight;
    var newwidth;
    var F = document.getElementById(id);

    if (F.contentDocument) {
        newheight = F.contentDocument.documentElement.scrollHeight;
        newwidth = F.contentDocument.documentElement.scrollWidth;
    } else {
        newheight = F.contentWindow.document.body.scrollHeight;
        newwidth = F.contentWindow.document.body.scrollWidth;
    }

    if (newheight > 300) {
        F.height = (newheight) + "px";
        F.width = (newwidth) + "px";
    } else {
        setTimeout(function() { autoResize(id); }, 100);
    }
}

/*********************************************************
*  Tabbed panels switching
*********************************************************/
function TabbedPanel() {
    throw "Can not create new instance. TabbedPanel is static utility class.";
}

/*selectedTabId - id of tab element to change "selected" status/decoration/class
selectedPanelId - id of panel element to change visibility (corresponds to selectedTabId)
tabIdsArray - ids of all tab elements
panelIdsArray - ids of all panel elements
                     
NOTE: tabIdsArray and panelIdsArray should be ordered correspondingly!*/
TabbedPanel.switchToPanel = function(selectedTabId, selectedPanelId, tabIdsArray, panelIdsArray) {
    for (var i = 0; i < tabIdsArray.length; i++) {
        window.document.getElementById(tabIdsArray[i]).className = "";
        window.document.getElementById(panelIdsArray[i]).style.display = "none";
    }

    window.document.getElementById(selectedTabId).className = "sel";
    window.document.getElementById(selectedPanelId).style.display = "";
}
// end - Tabbed panels switching

/*********************************************************
*  Pager/Paged content (client side)
*********************************************************/
// constructor
/*
pagerInstanceName - when instantiating object in script, pass instance name here,
divPagerId - preformatted div element containing pager controls,
divPageId - div reserved for content swapping / page,
pagesServer - object instance that has pages array property and renderPage(pageIndex) method.
*/
Pager = function(pagerInstanceName, divPagerId, divPageId, pagesServer) {

    // properties' initializations
    this.pagerInstanceName = pagerInstanceName;

    this.divPagerId = divPagerId;
    this.pagesServer = pagesServer;
    this.selectedPage = 0;

    this.page = window.document.getElementById(divPageId)

    var pager = window.document.getElementById(divPagerId);

    var buttons = pager.getElementsByTagName("IMG");
    var btnFirst = buttons[0];
    var btnPrev = buttons[1];
    var btnNext = buttons[2];
    var btnLast = buttons[3];

    this.pagesList = pager.getElementsByTagName("SPAN")[0];

    if (this.pagesServer.pages.length > 0) {
        this.page.innerHTML = this.pagesServer.renderPage(0);
    }

    // hide pager if only one page
    if (this.pagesServer.pages.length <= 1) {
        try {
            pager.style.display = "none";
        } catch (ex) { }

        return;
    }

    // methods' definitions
    var objInstanceRef = this;

    this.first = function() {
        objInstanceRef.select(0);
    }

    this.prev = function() {
        if (objInstanceRef.selectedPage == 0)
            return;

        objInstanceRef.select(objInstanceRef.selectedPage - 1);
    }

    this.next = function() {
        if (objInstanceRef.selectedPage == objInstanceRef.pagesServer.pages.length - 1)
            return;

        objInstanceRef.select(objInstanceRef.selectedPage + 1);
    }

    this.last = function() {
        objInstanceRef.select(objInstanceRef.pagesServer.pages.length - 1);
    },

    this.select = function(pageIndex) {
        objInstanceRef.selectedPage = pageIndex;

        objInstanceRef.pagesList.innerHTML = "";
        for (var i = 0; i < objInstanceRef.pagesServer.pages.length; i++) {
            if (objInstanceRef.selectedPage == i)
                objInstanceRef.page.innerHTML = objInstanceRef.pagesServer.renderPage(i);

            objInstanceRef.pagesList.innerHTML += "<a href=\"javascript:void(0);\" onclick=\"" + objInstanceRef.pagerInstanceName + ".select(" + i + ");\"" + (objInstanceRef.selectedPage == i ? " class=\"selected\"" : "") + ">" + (i + 1) + "</a>";
        }
    }

    // button & pages event handlers registration
    btnFirst.onclick = this.first;
    btnPrev.onclick = this.prev;

    this.pagesList.innerHTML = "";
    for (var i = 0; i < this.pagesServer.pages.length; i++) {
        this.pagesList.innerHTML += "<a href=\"javascript:void(0);\" onclick=\"" + this.pagerInstanceName + ".select(" + i + ");\"" + (this.selectedPage == i ? " class=\"selected\"" : "") + ">" + (i + 1) + "</a>";
    }

    btnNext.onclick = this.next;
    btnLast.onclick = this.last;
}
// end - Pager/Paged content (client side)

/********************
*  Utility functions
*********************/
function relayClick(clickableId) {
    var clickable = window.document.getElementById(clickableId);
    if (clickable.click != null)
        clickable.click();
    else if (clickable.href != null)
        window.location = clickable.href;
}
// end - Utility functions

// jQuery sort implementation
jQuery.fn.sortX = (function() {
    var sort = [].sort;
    return function(comparator, getSortable) {
        getSortable = getSortable || function() { return this; };

        var placements = this.map(function() {
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,

            // Since the element itself will change position, we have to have some way of storing
            //its original position in the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function() {
                if (parentNode === this) {
                    throw new Error("You can't sort elements if any one is a descendant of another.");
                }
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
            };
        });

        return sort.call(this, comparator).each(function(i) {
            placements[i].call(getSortable.call(this));
        });
    };
})();

/****************
*  Statistics
****************/
// use selector
function addClickStat(selectorString, idLoc, idObjType) {
    $(selectorString).click(function() {
        biziStatClick_ajax(idLoc, idObjType, '', '', '');
        return true;
    });
}
function addClickStatWithRegNum(selectorString, idLoc, idObjType, regNum) {
    $(selectorString).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, '', '');
        return true;
    });
}
function addClickStatWithDetails(selectorString, idLoc, idObjType, regNum, details) {
    $(selectorString).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, details, '');
        return true;
    });
}
function addClickStatWithPosition(selectorString, idLoc, idObjType, regNum, details, position) {
    $(selectorString).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, details, position);
        return true;
    });
}
// use object
function addClickStatObj(object, idLoc, idObjType) {
    $(object).click(function() {
        biziStatClick_ajax(idLoc, idObjType, '', '', '');
        return true;
    });
}
function addClickStatObjWithRegNum(object, idLoc, idObjType, regNum) {
    $(object).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, '', '');
        return true;
    });
}
function addClickStatObjWithDetails(object, idLoc, idObjType, regNum, details) {
    $(object).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, details, '');
        return true;
    });
}
function addClickStatObjWithPosition(object, idLoc, idObjType, regNum, details, position) {
    $(object).click(function() {
        biziStatClick_ajax(idLoc, idObjType, regNum, details, position);
        return true;
    });
}
function biziStatClick_ajax(idLoc, idObjType, regNum, details, position) {
    $.ajax({
        type: "POST",
        url: "Stats.aspx/AddClicked",
        async: false,
        data: "{'idLoc':'" + idLoc + "','idObjType':'" + idObjType + "','regNum':'" + regNum + "','details':'" + details + "','position':'" + position + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(msg) { }
    });
}
function biziStatShown_ajax(idLoc, idObjType, regNum, details, position) {
    $.ajax({
        type: "POST",
        url: "Stats.aspx/AddShown",
        async: false,
        data: "{'idLoc':'" + idLoc + "','idObjType':'" + idObjType + "','regNum':'" + regNum + "','details':'" + details + "','position':'" + position + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(msg) { }
    });
}

/****************************
* ModalMessage.js
****************************/
function showAlert(msg) {
    $.modal('<div style="width: 645px;">' +
                '<div style="padding: 0pt;" class="searchbox"> ' +
                    '<div class="searchbox-in">' +
                        '<h2 style="color: rgb(104, 131, 17);">' +
                            'Opozorilo' +
                        '</h2>' +
                        '<div class="sel-clasif">' +
                        '</div>' +
                    '</div>' +
                '</div>' +
                '<div style="padding: 1.5em 0em; text-align: center; width: 100%;">' +
                    msg +
                '</div>' +
                '<div style="float: right; padding-right: 300px;">' +
                    '<span class="button1 simplemodal-close">' +
                        '<a href="javascript:void(0);">V redu</a>' +
                    '</span>' +
                '</div>' +
            '</div>',
            { minHeight: null });
}
