﻿jQuery.download = function (url, data, method) {
    //url and data options required
    if (url && data) {
        //data can be string of parameters or array/object
        data = typeof data == 'string' ? data : jQuery.param(data);
        //split params into form inputs
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        //send request
        jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
		.appendTo('body').submit().remove();
    };
};

var isIE6 = false;

//Toolbox
var floatingToolbox = true;
var toolboxTimer;
var toolboxAutoCloseTimer;
var toolboxTimerDuration = 1000;
var toolboxAutoCloseDuration = 4000;
var toolboxOpeningSpeed = 'fast';
var toolboxClosingSpeed = 'normal';
var toolboxAutoClosingSpeed = 1000;
var toolboxMarginRight;
var toolboxRollover = false; //Flag when the mouse is over the toolbox
var toolOpen = false; //Flag when a tool is open
var dimscreenActive = false; //Flag when the screen is greyed out
var dimscreenSpeed = 200;
var dimscreenOpacity = 0.5;
var overlayContainerId = 'toolbox_wrapper';
var fileCollectorSpeed = 2000;

function FileCollector(id, title, size, extension, path) {
    //add file to profile
    window.setTimeout('OpenToolbox("slow")', toolboxTimerDuration);   
    $("li#icon-filecollector img").attr("src", "/images/add-to-filecollector.png");
    $.ajax({
        url: "/RemoteQueries/FileCollector.ashx",
        global: false,
        type: "POST",
        data: ({ action: "add", fileId: id }),
        dataType: "html",
        success: function (msg) {            
            $('#scroll-content').jScrollPane();
            window.setTimeout('CloseToolbox(' + fileCollectorSpeed + ')', fileCollectorSpeed);
            window.setTimeout('$("li#icon-filecollector img").attr("src", "/images/filecollector-icon.png")', toolboxAutoCloseDuration);
            _gaq.push(['_trackEvent', 'FileCollector', 'Add', title + ' -- ' + path]);
        },
        error: function (msg) {            
            $('#scroll-content').jScrollPane();
            window.setTimeout('CloseToolbox(' + fileCollectorSpeed + ')', fileCollectorSpeed);
            window.setTimeout('$("li#icon-filecollector img").attr("src", "/images/filecollector-icon.png")', toolboxAutoCloseDuration);
        }
    }
    );

}

function DirectDownload(aObj) {
    var title = $(aObj).attr("title");
    var path = $(aObj).attr("href");    
    _gaq.push(['_trackEvent', 'FileCollector', 'Direct Download', title + ' -- ' + path]);  
}

function DownloadFile(path, extension, title) {
    _gaq.push(['_trackEvent', 'FileCollector', 'Download', title + ' -- ' + path]);     
}

function RemoveFile(id,title,path) {    //add file to profile

    $.ajax({
        url: "/RemoteQueries/FileCollector.ashx",
        global: false,
        type: "POST",
        data: ({ action: "remove", fileId: id }),
        dataType: "html",
        success: function (msg) {            
            $('#tool_filesCollector .tool-container').html(msg);
            $('#scroll-content').jScrollPane();
            _gaq.push(['_trackEvent', 'FileCollector', 'Delete', title + ' -- ' + path]);
        }
    }
    );
    
}


$(document).ready(function () {
    setToolboxZindex();
    if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
        isIE6 = true;
    }

    // Fix IE6 background image caching problem
    if (isIE6) {
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch (err) { }
    }

    HeadShadow();
    PlaceFooter();
    $(window).resize(positionFooter)
    InitToolbox();
    DrawButtons();
    DrawColoredPanels();
    FixBottomPanels();
    
    $(".main-menu ul.level1 li").hover(function () {
        //vale to background
        if ($(this).find('.sub-menu ul').length != 0) {
            $(this).css('background', 'transparent url(/images/menu-selector.png) no-repeat bottom center');
            $(this).find('.sub-menu').show();
            $('.slideshow-small:visible').cycle({
                fx: 'zoom', random: 1, sync: 0,
                delay: -2000 // choose your transition type, ex: fade, scrollUp, shuffle, etc...
            });
        }
    }, function () {
        //vgale to background
        $(this).css('background', 'transparent none no-repeat bottom center');
        $(this).find('.sub-menu').hide();
    });

});








//--------------------------------------------- Toolbox
function IE6FixToolbox() {
    var offset = 110; // set offset (likely equal to your css top)
    $('#toolbox_links').css('top', (document.documentElement.scrollTop + offset) + 'px');
}

function InitToolbox() {
    
    toolboxMarginRight = $('#toolbox_links').css('marginRight');
    
    //IE6 fixed position simulation
    if (floatingToolbox) {        
        $('#toolbox').scrollFollow({
            offset: 25
        });
    }
    

    
    //Hover the toolbox
    $('#toolbox').hover(function () {
        toolboxRollover = true;
        OpenToolbox(toolboxOpeningSpeed);
    }, function () {
        if (!toolOpen) {
            toolboxTimer = window.setTimeout('CloseToolbox("' + toolboxClosingSpeed + '")', toolboxTimerDuration);
        }
        toolboxRollover = false;
    });


    //Open a tool
    $('#toolbox_content a').click(function () {
        //Close the other tools and open the current one
        if (toolOpen) {
            if ($(this).hasClass("submit-button")) {
                //do not close the tool
            }
            else {
                CloseTool($('div.toolbox-tools'));                
            }
        }
        if ($(this).hasClass("opening")) {
            OpenTool($(this));
            toolOpen = true;
            return false;
        }
        return true;
    });



    //Close the toolbox if clicking somewhere else on the page
    $(document).click(function (event) {
        var target = $(event.target);
        if (!target.is('#toolbox') && !target.parents('#toolbox').length) {
            if (dimscreenActive) {
                $.dimScreenStop(function () {                    
                    dimscreenActive = false;
                    CloseToolbox(toolboxClosingSpeed);
                });
            } else {
                CloseTool($('div.toolbox-tools'));
                CloseToolbox(toolboxClosingSpeed);                
            }
        }
    });

    //Auto-open the toolbox activated (and then close)
    if ($('#toolbox').hasClass('default_opened')) {        
        window.setTimeout('OpenToolbox("slow")', toolboxTimerDuration);
        if (!toolOpen) {            
            window.setTimeout('CloseToolbox(' + toolboxAutoClosingSpeed + ')', toolboxAutoCloseDuration);
        }
    }
}

function DownloadZip() {    
    CloseTool($('div.toolbox-tools'));
    CloseToolbox(toolboxClosingSpeed);
    $.download('/RemoteQueries/FileCollector.ashx', 'action=download');
    _gaq.push(['_trackEvent', 'FileCollector', 'Download Zip', 'all-files']);     
}
//Open the toolbox
function OpenToolbox(speed) {
    window.clearTimeout(toolboxTimer);
    try {
        $('#toolbox').stop().animate({
            marginRight: 0
        }, speed)();
    } catch (err) { }
}

//Close the toolbox
function CloseToolbox(speed) {    
    if (!toolboxRollover && !toolOpen) {
        toolOpen = false;
        $('#toolbox').stop().animate({
            marginRight: -170
        }, speed);
    }
}

function OpenTool(linkTool) {
    var tool = $("#tool_" + $(linkTool).attr("id"));
    var useAjaxLoad = tool.hasClass('remote');    
    if (useAjaxLoad == true) {
        //console.log('Initial chart loading');

        //Open the tool          
        tool.css('visibility', 'visible');
        tool.css('z-index', '4010');
        
        //Load the tool content via AJAX
        $.ajax({
            type: "GET",
            url: linkTool.attr('href'),
            dataType: "html",
            success: function (html) {
               // alert(html);
                tool.find('.tool-container').html(html);
                $('#scroll-content').jScrollPane();
            },
            error: function () {
            },
            complete: function () {

            }
        });

    } else {       
        tool.css('visibility', 'visible');
    }
     
}

//Close a tool
function CloseTool(tool) {
    tool.css('visibility', 'hidden');
    toolOpen = false;
}
function AddToFavorites() {
    var ns = "Netscape and FireFox users, use CTRL+D to bookmark this site.";
    if ((navigator.appName == 'Microsoft Internet Explorer') &&
    (parseInt(navigator.appVersion) >= 4)) {
        window.external.AddFavorite(document.URL, document.title);
    }
    else if (navigator.appName == 'Netscape') {
        alert(ns);
    }
}


function HeadShadow() {
    if (isIE6) return;
    $("#head-shadow").show();
}
function PlaceFooter() {
    //var pageHeight = $(window).height();    
   // $("#footer").css("top:" + pageHeight);
    //$("#footer").show();
    positionFooter();
}


function positionFooter() {
    //alert($(window).scrollTop() + $(window).height());
    //alert($(document).height());
    if ($(window).height() >= $(document).height()) {
        $("#footer").css({ position: "absolute", top: ($(window).height() - $("#footer").height()) + "px" })
    }
}



$(function () {
    $(".datepicker").datepicker($.datepicker.regional[current_locale]);
});
function DrawButtons() {
    $('.button').each(function (index) {
        $(this).html($(this).html() + "<div class='button-left'>&nbsp;</div><div class='button-right'>&nbsp;</div>'");    
    });

}
function DrawColoredPanels() {
    $('.panel.round-panel').each(function (index) {
        $(this).html($(this).html() + "<div class='tr'>&nbsp;</div><div class='tl'>&nbsp;</div><div class='bl'>&nbsp;</div><div class='br'>&nbsp;</div>");
    });
}
function FixBottomPanels() {
    $('#bottom .panel').each(function (index) {
        if (index % 2 == 1) {
            $(this).css("float","right");
        }
    });
}


function checkRegexp(o, regexp) {
    if (!(regexp.test(o))) {
        return false;
    } else {
        return true;
    }
}
function isEmail(str) {
    return checkRegexp(str, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return true;
}

function SendToAFriend(strEmailFrom,strEmailTo, strNotes,returnFunction) {    
    $.ajax({
        url: "/RemoteQueries/EmailToAFriend.ashx",
        global: false,
        type: "POST",
        data: ({ emailfrom: strEmailFrom, emailto: strEmailTo, notes: strNotes }),
        dataType: "html",
        success: function (msg) {
            returnFunction();
        },
        error: function (msg) {
            returnFunction();
        }
    }
    );
}
function fnTrapEnter() {
    if (event.keyCode == 13) {
        SearchKeyword();
        event.returnValue = false;
    }
}
function SearchKeyword() {
    var t = $("#input-keyword").val();
    //t = t.replace("&", "and").replace("<", " ").replace(">", " ")
    var linkToSearch = $("#link-to-search").attr("href");
    if ((t != "") && (linkToSearch!="")) {
        document.location = linkToSearch + "/?q=" + escape(t);
    }
    return false;
}

function DecimalToString(dec) {
    var value = new String(dec);
    if (current_locale == "el-GR"){
        return value.replace(".", ",");
    }
    return value;
}

function setToolboxZindex() {
    var item = $("#toolbox");
    //createBackgroundIframe(item,false);
    $('.toolbox-tools').each(function (index) {
        createBackgroundIframe($(this),true);
    });
    
    $('#toolbox #toolbox_links').css("z-index", 3010);
    $('#toolbox #toolbox_content').css("z-index", 3010);
    $('.toolbox-tools').css("z-index", 4020);
    $('.toolbox-tools .inner').css("z-index", 4030);    
    if (navigator.userAgent.indexOf("Firefox") == -1) {
        $('.toolbox-tools .inner').css("background", "transparent url('/Images/toolbox.gif') no-repeat center center");
    }
    $('.toolbox-tools .inner').css("min-height", $('.toolbox-tools').height());
    $('.toolbox-tools .inner').css("height", $('.toolbox-tools').height());
    
}
function createBackgroundIframe(item,addblankImage) {

    var height = $(item).height();
    var width = $(item).width();
    var hh = $(item).html();
    $(item).html("");
    var iframe = "<iframe width='" + width + "' scrolling='no' src='about:blank' frameborder='0' height='" + height + "' style='display:block;height:" + height + "px;border:0px solid #ffffff;position:relative;top:0;left:0;margin:0 0;padding:0 0' class='iframe-background'/>";
    $(item).append(iframe);
    var newDiv;
    newDiv = "<div style='display:block;background-color:#cccccc;position:absolute;min-height:" + height + ";height:auto! important;width:" + width + "px;height:" + height + "px;top:0;left:0;' class='inner'>" + hh + "</div>";
   
    $(item).append(newDiv);
    
}
