﻿/// <reference path="jquery-1.2.6-vsdoc.js" />
var _IE_OPERA = typeof (document.all) != 'undefined';
var _OPERA_FF = typeof (window.pageXOffset) != 'undefined';
var _OPERA = window.opera;
var _IE = !_OPERA && _IE_OPERA;
var _FF = !_OPERA && _OPERA_FF;
var _IE7 = _IE && (typeof (window.XMLHttpRequest) != 'undefined');
var _IE6 = _IE && !_IE7

var firstRun = true;
var postCache = {};
var appDir = '';
var href = new locationMaker(location);
 //tested
function locationMaker(locRef) {
    this.loc = locRef;
    this.set = function(href) {
        this.loc.href = href;
    }
    this.get = function() {
        return this.loc.href;
    }
}

function addToFavourites(title, url) {
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    } else if (window.opera && window.print) {
        return true;
    } else if (document.all) {
        window.external.AddFavorite(url, title);
    }
}

function setAsHomepage(sender, url) {
    if (document.all) {
        sender.style.behavior = 'url(#default#homepage)';
        sender.setHomePage(url);
    } else {
    }
}
//tested
function getApplicationDirectory() {
    return $('#menucontainer a:first').attr('href').replace(/^(http.*)?#/, '').replace(/EVestnik.*$/, '');
}
//tested
function getPathFromNormalUrl(url) {
    return url.replace(/http:\/\/[^\/]+\//i, '');
}
//tested
function getDomain() {
    return window.location.href.match(/^http:\/\/[^\/]+\//)[0];
}

function onDomCreated() {
    $('#container').append($("<img id='loading' src='" + getDomain() + "img/loading.gif' style='position:absolute;top:200px;left:360px;z-index:99;' />"));
    $.ajaxSetup({ contentType: "application/x-www-form-urlencoded; charset=utf-8", scriptCharset: "utf-8" });
    $.historyInit(surfTo);
    rewriteLinks();
    appDir = getApplicationDirectory();
    $('#loading').hide();
}
//tested
function surfTo(url) {
//    if (url == '')
    //        return;
    if (firstRun) {
        firstRun = false;
        if(url == '')
            return;
    }
    if (/^\//.test(url)) {
        var cachedForm = postCache[getPostName(url)];
        cachedForm["page"] = url.replace(/.*\|/, '');
        $('#loading').show();
        $.post(url.replace(/\|.*/, ''), cachedForm, afterPostHandler);
    }
    else {
        if (isTheSameVestnikView(url)) {
            loadCorrectVestnikPart(url);
            removePopup();
            return;
        }

        if (!dontReloadMain(url)) {
            $('#loading').show();
            $.get('/' + url, afterGetHandler);
        }
    }
}
//tested
function afterPostHandler(data) {
    var innerMain = getContainerToLoadToAfterPost(postCache[getPostName(href.get())]);
    innerMain.html("").append(data);
    if (innerMain.find('form').length)
        fillInForms(href.get(), innerMain);
    onContentLoaded(innerMain);
    $('#loading').hide();
}
//tested
function afterGetHandler(data) {
    var innerMain = getContainerToLoadToAfterGet(href.get());
    innerMain.html("").append(data);
    if (getPostName(href.get()) != '' && innerMain.find('form').length)
        fillInForms(href.get(), innerMain);
    onContentLoaded(innerMain);
    $('#loading').hide();
}

function onContentLoaded(element)
{
    rewriteLinks(element);
    rewriteDates(element);
}

function rewriteDates(element)
{
    $(element).find('input[valueType=date]').datepick({showAnim: ''});/*, onClose: function(){
        var thisvalue = this.value;
        if(thisvalue == '')
            return;
        $(this).parent().find('input[valueType=date]').each(function(){
            if(this.value == '')
                this.value = thisvalue;
        });
    }});*/
}

//tested
function getContainerToLoadToAfterPost(cachedForm) {
    if (typeof (cachedForm['cpv_submit']) != 'undefined' || typeof (cachedForm['nuts_submit']) != 'undefined' || typeof (cachedForm['delete']) != 'undefined')
        return getWhitePopup();
    else
        return removePopupReturnMain();
}
//tested
function getContainerToLoadToAfterGet(url) {
    if (/Vyhladavanie\/SearchCpv/.test(url) || /Vyhladavanie\/SearchNuts/.test(url)) {
        if ($('#popup').length)
            return $('#popup');
        else
            return getWhitePopup();
    } else
        return removePopupReturnMain();
}
//tested
function getWhitePopup() {
    if ($('#popup').length)
        return $('#popup');
    var whiteHider = $("<div id='white'></div>");
    var container = $("<div><div id='outerPopup'><a class='close' id='outerPopupClose' href='#Vyhladavanie/Oznamenie'>x</a><div id='popup'></div></div></div>"); //
    $('#container').append(whiteHider).append(container);
    $('#outerPopupClose', container).bind('click', function(e) { onclickEventHandler(e, this); });
    $('#white').css({ 'opacity': 0.5, height: $('#container').height() });
    if (_IE6)
        $('select').hide().after('<input class="fake" />');
    return $('#popup', container);
}
//tested
function removePopupReturnMain() {
    removePopup();
    return $('#innerMain');
}
//tested
function isTheSameVestnikView(url) {
    if (/EVestnik\/Aktualne/.test(url)) {
        if ($('#innerMain h1').length)
            return ($('#innerMain div.category').length);
    } else if (/EVestnik\/Vestnik/.test(url)) {
        if (!$('#innerMain h1').length)
            return ($('#innerMain div.category').length);
    }
    return false;

}

function loadCorrectVestnikPart(url) {
    var categoriesMatcher = url.match(/cat=(\d+(\.\d+)*)/);
    var categories = categoriesMatcher == null ? "" : categoriesMatcher[1];

    for (var i = 0; i < 12; i++) {
        var cElements = $("#innerMain div.category[cat='" + i + "'] div");
        if (("." + categories + ".").indexOf("." + i + ".") > -1 && (!cElements.length || cElements[0].style.display == 'none')) {
            if (cElements.length)
                cElements.show();
            else {
                $('#loading').show();
                $.get('/' + appDir + 'EVestnik/VestnikCategory/' + i + '?' + url.match(/(date=[^&]*)(&|$)/)[1], function(data) {
                    var ii = this.url.match(/VestnikCategory\/(\d+)\?/)[1];
                    $("#innerMain div.category[cat='" + ii + "']").append(data);
                    rewriteLinks("#innerMain div.category[cat='" + ii + "'] div");
                    $('#loading').hide();
                });
            }
            rewriteVestnikViewLinks(i);
        } else if (("." + categories + ".").indexOf("." + i + ".") == -1 && cElements.length && cElements[0].style.display != 'none') {
            cElements.hide();
            rewriteVestnikViewLinks(i);
        }
    }
}
//tested
function rewriteVestnikViewLinks(i) {
    $('#innerMain a').attr('href', function() {
        var reg = RegExp('(#.*)cat=' + i + '(&|$)', 'i');
        if (reg.test(this.href)) {
            var matcher = this.href.match(reg);
            return this.href.replace(reg, matcher[1] + matcher[2]).replace('?&', '?').replace(/&$/, '');
        }
        reg = RegExp('(#.*cat=)' + i + '\\.', 'i');
        if (reg.test(this.href)) {
            var matcher = this.href.match(reg);
            return this.href.replace(reg, matcher[1]);
        }
        reg = RegExp('(#.*cat=[^&]*)\\.' + i + '(\\.|&|$)', 'i');
        if (reg.test(this.href)) {
            var matcher = this.href.match(reg);
            return this.href.replace(reg, matcher[1] + matcher[2]);
        }
        else {
            if (/#.*cat=/.test(this.href)) {
                var matcher = this.href.match(/(#.*cat=)/);
                return this.href.replace(/#.*cat=/, matcher[0] + i + '.');
            } else {
                if (/#.*\?/.test(this.href))
                    return this.href + '&cat=' + i;
                else
                    return this.href + '?cat=' + i;
            }
        }
    });
}
//tested at least partially
function rewriteLinks(element) {
    var linksToRewrite = typeof (element) == 'undefined' ? $('a') : $(element).find('a');
    linksToRewrite.attr("href", function()
    {
        //this should be refactored, i dont like that it's on two places (here and 5 lines down)
        if (/#/.test(this.href) || /InformaciePdf/.test(this.href) || /Ulozit/.test(this.href))
            return this.href;
        return "#" + getPathFromNormalUrl(this.href);
    }).bind('click', function(e)
    {
        if (/InformaciePdf/.test(this.href) || /Ulozit/.test(this.href) || /#$/.test(this.href))
            return;
        return onclickEventHandler(e, this);
    });
    var inputsToRewrite = typeof (element) == 'undefined' ? $('input[type="submit"], input[type="image"]') : $(element).find('input[type="submit"]').add($(element).find('input[type="image"]'));
    inputsToRewrite.bind('click', submitClicked);
}
//tested
function onclickEventHandler(e, element) {
    $.historyLoad(element.href.replace(/.*#/, '').replace(/^http:.*/, ''));
    selectMenuIfMenuClicked(element);
    return false;
}
//tested
function selectMenuIfMenuClicked(element) {
    if ($(element).parents("#menucontainer").length > 0) {
        $('#menucontainer a').removeClass('selected');
        $(element).addClass('selected');
    }
}
//tested
function submitClicked(e) {
    var element = $(this);
    element.parents("form").unbind().submit(function() {
        //this == form to submit
        $.historyLoad(this.getAttribute("action") + '|' + saveParamsReturnPage(element));
        return false;
    }).trigger('submit');
    return false;
}
//tested
function saveParamsReturnPage(el) {
    var form = el.parents('form');
    var params = {};
    $("input[type='text'], input[type='hidden'], textarea", form).each(function() {
        params[this.name || this.id || this.parentNode.name || this.parentNode.id] = this.value;
    });
    $("option:selected", form).each(function() {
        params[this.parentNode.name || this.parentNode.id] = this.value;
    });
    if (el.attr('name') != '')
        params[el.attr('name')] = '';
    var postName = getPostName(form.attr("action"));
    postCache[postName] = params;
    if (typeof (params["page"]) == 'undefined')
        params["page"] = 0;
    return params["page"];
}
//tested
function getPostName(url) {
    if (/#.*Vyhladavanie\/Search/.test(url) || /Vyhladavanie\/Search[^#]*$/.test(url))
        return 'oznamenievestnik';
    return getPostNameNotSearchedYet(url);
}

function getPostNameNotSearchedYet(url) {
    if (/#.*Vyhladavanie\/OznamenieVestnik/.test(url) || /Vyhladavanie\/OznamenieVestnik[^#]*$/.test(url))
        return 'oznamenievestnik';
    return "";
}

function fillInForms(url, data) {
    var formType = '';
    formType = getPostNameNotSearchedYet(url);
    if (formType == '' || typeof (postCache[formType]) == 'undefined')
        return;
    var postData = postCache[formType];
    postData.get = get;
    data.find('#rozsah')[0].value = postData.get('rozsah');
    data.find('#miesto')[0].value = postData.get('miesto');
    data.find('#cislo_oznamenia')[0].value = postData.get('cislo_oznamenia');
    data.find('#datum_uverejnenia_od')[0].value = postData.get('datum_uverejnenia_od');
    data.find('#datum_uverejnenia_do')[0].value = postData.get('datum_uverejnenia_do');
    data.find('#konecny_termin_od')[0].value = postData.get('konecny_termin_od');
    data.find('#konecny_termin_do')[0].value = postData.get('konecny_termin_do');
    data.find('#lehota_vyziadania_podkladov_do')[0].value = postData.get('lehota_vyziadania_podkladov_do');
    data.find('#lehota_vyziadania_podkladov_od')[0].value = postData.get('lehota_vyziadania_podkladov_od');
    data.find('#druh_zakazky')[0].value = postData.get('druh_zakazky');
    data.find('#kod_oznamenia')[0].value = postData.get('kod_oznamenia');
    data.find('#rok')[0].value = postData.get('rok');
    data.find('#cislo')[0].value = postData.get('cislo');
    data.find('#druh_postupu')[0].value = postData.get('druh_postupu');
    if (data.find('#cpv')[0].value == '')
        data.find('#cpv')[0].value = postData.get('cpv');
    if (data.find('#nuts')[0].value == '')
        data.find('#nuts')[0].value = postData.get('nuts');
    data.find('#nazov_obstaravatela')[0].value = postData.get('nazov_obstaravatela');
    data.find('#text')[0].value = postData.get('text');
}
//tested
function get(key)
{
    if(typeof this[key] == 'undefined')
        return '';
    return this[key];
}
//tested
function dontReloadMain(url) {
    if (!/Vyhladavanie\/SearchCpv/.test(url) &&!/Vyhladavanie\/SearchNuts/.test(url) && $('#outerPopup').length) {
        removePopup();
        return true;
    }
    return false;
}
//tested
function removePopup() {
    $('#white').remove();
    $('#outerPopup').parent().remove();
    if (_IE6) {
        $('select').show();
        $('input.fake').remove();
    }
}

function writeDebug(text) {
    //$('#debugdiv').html($('#debugdiv').html() + '<br/>' + text);
}
