/*
 * params:
 *      - title           : string az aktualis ablak cimsora
 *      - type            : modal,confirm,alert  egyenlore csak a modal
 *      - width           : az ablak szelessege ha nincs megadva akkor a def ertek 300px
 *      - height          : az ablak magassaga  ha nincs megadva akkor a def ertek 200px
 *      - max_height      :
 *      - max_width       :
 *      - movable         : boolean - window movable      - default true
 *      - icon            : string  - the image path
 *      - resizable       : boolean - resize window       - default false
 *      - escape          : boolean - esc to close window - default true
 *      - overlay         : boolean - dispay overlay div  - default true
 *      - buttons         : array   - set window buttons  - default {'minimize':true,'maximize':true,'close':true}
 *      - content_icon    : string  - set alert window content icon - default images/alert_icon.gif
 *      - overlay_color   :
 *      - overlay_opacity : 0-1
 *      - button_ok       : string
 *      - button_yes      :
 *      - button_no       :
 *      - callback        :
 */
var theme = '';
var content_icon = '';
var lang = '';
var window_params;
var undefined;
var imgLoader = new Image();
$(document).ready(function(){
    ___getVariables();
    imgLoader.src = css_path+theme+'/images/loadingAnimation.gif';
    window_init();
});
function window_init()
{
    insert_css();
    $.ajaxSetup({async: false});
    $('body').ajaxError(function(event, request, settings){i18n={'close':'Close','maximize':'Maximize','minimize':'Minimize','restore':'Restore'};});
    $.getScript(js_path+"window/i18n/"+lang+".js");
    $.getScript(js_path+"window/ui.core.js");
    $.getScript(js_path+"window/ui.draggable.js");
    $.getScript(js_path+"window/ui.resizable.js");
    $.getScript(js_path+"window/excanvas.js");
    $.ajaxSetup({async: true});
}
function window_show(params)
{
    window_params = params;
    display_loader();
    set_default_values();
    if (params['overlay']) window_overlay();
    if ( $("#window_container").length == 0 )
    {
        $('body').append('<div id="window_container">\n\
                    <div id="window_window">\n\
                       <table id="window_table">\n\
                    <tr>\n\
                        <td class="top_left"></td>\n\
                        <td class="top_center" id="window_title_container">\n\
                            <span id="window_title"></span>\n\
                        </td>\n\
                        <td class="top_right"></td>\n\
                    </tr>\n\
                    <tr>\n\
                        <td class="content_left"></td>\n\
                        <td class="content_center" valign="top">\n\
                            <div id="window_content">\n\
                            </div>\n\
                        </td>\n\
                        <td class="content_right"></td>\n\
                    </tr>\n\
                    <tr>\n\
                        <td class="bottom_left"></td>\n\
                        <td class="bottom_center">&nbsp;</td>\n\
                        <td class="bottom_right"></td>\n\
                    </tr>\n\
                </table>\n\
				</div>\n\
				</div>');

        if (window_params['icon']!=undefined){
            $('#window_title').append('<span style="float:left" id="title_icon"></span>&nbsp;');
            $('#title_icon').css({"width":"16px","height":"16px","background-image":"url("+window_params['icon']+")"})
        }
        $('#window_title').append(window_params['title']);
        setup_buttons();
        disSel = document.getElementById('window_title_container');
        disableSelection(disSel);
        if (window_params['type']=='modal') setup_modal_content();
        if (window_params['type']=='alert') setup_alert_content();
        if (window_params['type']=='confirm') setup_confirm_content();
        if (window_params['type']!='modal')
        {
            display_window();
        }else{
			display_window(); 
			/*$("#window_window").load(param,function(){//to do a post change this load method
				display_window(); 
			});*/
        }
    }
}
function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	target.style.cursor = "default"
}
function display_window()
{
    $('#window_title').css({"height":"16px"});
    $('.top_left').css('margin','0').css('padding','0');
    $('.content_left').css('margin','0').css('padding','0');
    $('.bottom_left').css('margin','0').css('padding','0');
    $('.top_right').css('margin','0').css('padding','0');
    $('.content_right').css('margin','0').css('padding','0');
    $('.bottom_right').css('margin','0').css('padding','0');
    var arrPageSizes = ___getPageSize();
    $('#window_container').css({width:arrPageSizes[2],height:arrPageSizes[3]}).show();
    if (window_params['movable']) make_window_moveable();
    if (window_params['resizable']) make_window_resizable();
    $('#window_window').css({"width":window_params['width'],"height":window_params['height']});
    set_window_top();
    $('#window_window').toggle('slow',function(){});
    $(window).resize(function(){set_window_top();});
    $(window).scroll(function(){set_window_top();calculate_overlay()});
    if (window_params['escape']) set_escape();
    $('#window_loader').remove();
}
function calculate_overlay()
{
    if (window_params['overlay'])
    {
        var arrPageScroll = ___getPageScroll();
        $('#window_hideselect').css({
                top:arrPageScroll[1],
                left:arrPageScroll[0]
            });
        $('#window_overlay').css({
                top:arrPageScroll[1],
                left:arrPageScroll[0]
        });
    }
}
function display_loader()
{
    $("body").append("<div id='window_loader'><img src='"+imgLoader.src+"' /></div>");
    $('#window_loader').show();
}
function set_default_values()
{
    if (window_params['escape']==undefined) window_params['escape']=true;
    if (window_params['resizable']==undefined) window_params['resizable']=false;
    if (window_params['overlay']==undefined) window_params['overlay']=true;
    if (window_params['overlay_color']==undefined) window_params['overlay_color']='#cccccc';
    if (window_params['overlay_opacity']==undefined) window_params['overlay_opacity']=0.75;
    if (window_params['type']=='modal') set_modal_default_values()
    if (window_params['type']=='alert') set_alert_default_values()
    if (window_params['type']=='confirm') set_cofirm_default_values()
    sizes = ___getPageSize();
    if (window_params['max_width']==undefined) window_params['max_width']= sizes[2];
    if (window_params['max_height']==undefined) window_params['max_height']= sizes[3];
    if(window_params['max_width']<window_params['width']) window_params['max_width']=window_params['width'];
    if(window_params['max_height']<window_params['height']) window_params['max_height']=window_params['height'];
    if (window_params['movable']==undefined) window_params['movable']= true;

}
function set_cofirm_default_values()
{
    if (window_params['title']==undefined) window_params['title']='confirm';
    set_buttons_default_values(false,false,true);
    if (window_params['width']==undefined) window_params['width']= 300;
    if (window_params['height']==undefined) window_params['height']= 100;
    if (window_params['content_icon']==undefined) window_params['content_icon']= content_icon;
    window_params['resizable']=false;
    if (window_params['button_yes']==undefined) window_params['button_yes']= 'Yes';
    if (window_params['button_no']==undefined) window_params['button_no']= 'No';
    window_params['escape']=true;
}
function set_alert_default_values()
{
    if (window_params['title']==undefined) window_params['title']='alert';
	set_buttons_default_values(false,false,true);
    if (window_params['width']==undefined) window_params['width']= 300;
    if (window_params['height']==undefined) window_params['height']= 100;
    if (window_params['content_icon']==undefined) window_params['content_icon']= content_icon;
    window_params['resizable']=false;
    if (window_params['button_ok']==undefined) window_params['button_ok']= 'Ok';
    window_params['escape']=false;
}
function set_modal_default_values()
{
    if (window_params['title']==undefined) window_params['title']='window';
    set_buttons_default_values(true,true,true);
    if (window_params['width']==undefined) window_params['width']= 300;
    if (window_params['height']==undefined) window_params['height']= 200;
}
function set_buttons_default_values(minimize,maximize,close)
{
    if (window_params['buttons']==undefined) window_params['buttons']={'minimize':minimize,'maximize':maximize,'close':close};
    if (window_params['buttons']['close']==undefined) window_params['buttons']['close']=close;
    if (window_params['buttons']['maximize']==undefined) window_params['buttons']['maximize']=maximize;
    if (window_params['buttons']['minimize']==undefined) window_params['buttons']['minimize']=minimize;
}
function setup_alert_content()
{
    $('#window_title').addClass('alert_content');
    $('#window_content').addClass('alert_content');
    $('#window_content').append('<table width="100%"><tr><td><p class="a_c"></p></td></tr></table>');
    if(window_params['content_icon']!=false) $('.a_c').append('<img src="'+window_params['content_icon']+'" align="left"/>')
    $('.a_c').append(window_params['content']);
    $('#window_content').append('<p><button id="alert_button">'+window_params['button_ok']+'</button></p>');
    $('#alert_button').click(function(){window_remove();});
}
function setup_confirm_content()
{
    $('#window_title').addClass('confirm_content');
    $('#window_content').addClass('confirm_content');
    $('#window_content').append('<table width="100%"><tr><td valign="top" class="confirm_img"></td><td><p class="confirm_text"></p></td></tr></table>');
    if(window_params['content_icon']!=false) $('.confirm_img').append('<img src="'+window_params['content_icon']+'" align="left"/>')
    $('.confirm_text').append(window_params['content']);
    $('#window_content').append('<p class="buttons"><button id="confirm_window_button_yes">'+window_params['button_yes']+'</button><button id="confirm_window_button_no">'+window_params['button_no']+'</button></p>');
    $('#confirm_window_button_yes').click(function(){confirm_window_remove(true);});
    $('#confirm_window_button_no').click(function(){confirm_window_remove(false);});
}
function setup_modal_content(){
    if (window_params['url']!=undefined){
        $('#window_content').append('<iframe src="'+window_params['url']+'" width="100%" height="100%" style="overflow:hidden;position:relative;margin:0;padding:0;" allowTransparency="true" frameborder=0 scrolling="no"></iframe>')
        $('#window_content').css({'overflow':'hidden'});
    }else{
        if ($('#'+window_params['content']).length>0){
            $('#window_content').append($('#'+window_params['content']).html());
        }else{
            $('#window_content').append(window_params['content']);
        }
        $('#window_content').css({'overflow':'auto'});
    }
}
function setup_buttons()
{
    if (window_params['buttons']['close']){
        $('#window_title_container').append('<span style="float:right;cursor:pointer;cursor:hand;" title="'+i18n['close']+'" id="close_button"></span>');
        $('#close_button').click(function(){window_remove();});
    }
    if (window_params['buttons']['maximize']){
        $('#window_title_container').append('<span style="float:right;cursor:pointer;cursor:hand;" class="maximize_button" title="'+i18n['maximize']+'" id="maximize_button"></span>');
        $('#maximize_button').click(function(){window_maximize();});
    }
    if (window_params['buttons']['minimize']){
        $('#window_title_container').append('<span style="float:right;cursor:pointer;cursor:hand;" title="'+i18n['minimize']+'" id="minimize_button"></span>');
        $('#minimize_button').click(function(){window_minimize();});
        $('#window_title_container').dblclick(function(){window_minimize();})
    }
}
function window_minimize()
{
    $('#window_content').fadeOut('normal',function(){
        $('#maximize_button').unbind('click');
        $('#restore_button').unbind('click');
        if (window_params['resizable']) $('#window_window').resizable('disable');
        window_params['current_height']=$('#window_window').height();
        $("#window_window").animate({
            height:22
            }, 600,function(){
                $('#minimize_button').unbind('click');
                $('#minimize_button').click(function(){restore_from_minimized();})
                $('#window_title_container').unbind('dblclick');
                $('#window_title_container').dblclick(function(){restore_from_minimized();})
        });
    });
}
function restore_from_minimized()
{
    $("#window_window").animate({height:window_params['current_height']}, 600,function(){
        $('#maximize_button').click(function(){window_maximize();});
        $('#restore_button').click(function(){window_restore();});
        $('#window_content').fadeIn();
        if (window_params['resizable']) $('#window_window').resizable('enable');
        $('#minimize_button').unbind('click');
        $('#minimize_button').click(function(){window_minimize();})
        $('#window_title_container').unbind('dblclick');
        $('#window_title_container').dblclick(function(){window_minimize();})
    });
}
function window_maximize()
{
    var current_sizes = ___getPageSize();
    diff_l=(current_sizes[2]-window_params['max_width'])/2;
    diff_t=(current_sizes[3]-window_params['max_height'])/2;
    $("#window_window").animate({
        width: window_params['max_width'],
        height:window_params['max_height'],
        top:diff_t,
        left:diff_l
      }, 1000,function(){set_restore();});
}
function window_restore()
{
    var current_sizes = ___getPageSize();
    diff_l=(current_sizes[2]-window_params['width'])/2;
    diff_t=(current_sizes[3]-window_params['height'])/2;
    $("#window_window").animate({
        width: window_params['width'],
        height: window_params['height'],
        top:diff_t,
        left:diff_l
      }, 1000,function(){set_maximize();});

}
function set_maximize()
{
    $('#maximize_button').unbind('click');
    $('#maximize_button').removeClass('restore_button');
    $('#maximize_button').addClass('maximize_button');
    $('#maximize_button').attr('title',i18n['maximize']);
    $('#maximize_button').click(function(){window_maximize();});
}
function set_restore()
{
    $('#maximize_button').unbind('click');
    $('#maximize_button').removeClass('maximize_button');
    $('#maximize_button').addClass('restore_button');
    $('#maximize_button').attr('title',i18n['restore']);
    $('#maximize_button').click(function(){window_restore();});
}
function make_window_moveable()
{
    $('#window_window').draggable({cancel: '#window_content',containment: 'parent'});
}
function make_window_resizable()
{
    $('#window_window').addClass('ui-resizable');
    $('#window_window').resizable({animate:true,containment: 'document',maxWidth: window_params['max_width'],maxHeight: window_params['max_height'],minWidth: window_params['width'],minHeight: window_params['height']});
}
function window_overlay()
{
    $('body').append('<iframe id="window_hideselect"></iframe><div id="window_overlay"></div>');
    var arrPageSizes = ___getPageSize();
    var arrPageScroll = ___getPageScroll();
        $('#window_hideselect').css({
            top:arrPageScroll[1],
            left:arrPageScroll[0],
            width:arrPageSizes[2]+20,
            height:arrPageSizes[3]});
    $('#window_overlay').css({
            top:arrPageScroll[1],
            left:arrPageScroll[0],
            width:arrPageSizes[2]+20,
            height:arrPageSizes[3],
            opacity:window_params['overlay_opacity'],
            'background-color':window_params['overlay_color']
    }).fadeIn();
    $('body').attr('scroll','no');
    $('body').css({"overflow":"hidden"})
}
function set_window_top()
{
    var current_sizes = ___getPageSize();
    var arrPageScroll = ___getPageScroll();
    diff_l=(current_sizes[2]-$('#window_window').width())/2;
    diff_t=(current_sizes[3]-$('#window_window').height())/2;
    $('#window_window').css({top:diff_t,left:diff_l+arrPageScroll[0]});
    $('#window_container').css({top:arrPageScroll[1]})
}
function window_remove()
{
    var args = window_remove.arguments;
    refresh = args[0];
    $("#window_overlay").unbind("click");
    $("#window_window").toggle("slow",function(){
        $('#window_hideselect,#window_overlay,#window_container').remove();
        $('body').removeAttr('scroll');
        $('body').css({"overflow":"auto"})
        if (refresh == true)
        {
                cUrl = false;
                if (args[1] != 'undefined' && args[1] != null && args[1] != "") cUrl = true;
                if (cUrl)
                {
                        document.location = args[1];
                }else{
                        if (location.href.indexOf('#nowhere')>-1)
                            page_location = location.href.substring(0, location.href.length-8);
                        else
                            page_location =location.href;
                        document.location = page_location;
                }
        }
    });
  
}
function confirm_window_remove(value)
{
    $("#window_overlay").unbind("click");
    $("#window_window").toggle("slow",function(){
        $('#window_hideselect,#window_overlay,#window_container').remove();
        $('body').removeAttr('scroll');
        $('body').css({"overflow":"auto"})
        eval(window_params['callback']+'('+value+')');
    });
}
function set_escape()
{
    document.onkeydown = function(e){
        if (e == null) {keycode = event.keyCode;} else {keycode = e.which;}
        if(keycode == 27){window_remove();}
    };
}
function ___getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
            if(document.documentElement.clientWidth){
                    windowWidth = document.documentElement.clientWidth;
            } else {
                    windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
            pageHeight = windowHeight;
    } else {
            pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
            pageWidth = xScroll;
    } else {
            pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
}
function ___getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScroll,yScroll);
    return arrayPageScroll;
}
function ___getVariables(){
    var scripts = document.getElementsByTagName("script");
    var config=new Array();
    var rePkg = /window_svi\.js(\W|$)/i;
    for(var i = 0; i < scripts.length; i++){
        var src = scripts[i].getAttribute("src");
        if(!src){continue;}
        var m = src.match(rePkg);
        if(m){
                var cfg = scripts[i].getAttribute("sviConfig");
                if(cfg){
                        var cfgo = eval("({ "+cfg+" })");
                        for(var x in cfgo){
                                config[x] = cfgo[x];
                        }
                }
                break;
        }
    }
    theme=config['theme'];
    content_icon=config['css_path']+"window/themes/"+config['content_icon'];
    lang=config['lang'];
	js_path = config['js_path'];
	css_path = config['css_path'];
}
function insert_css()
{
    var headID = document.getElementsByTagName("head")[0];
    var cssNode_1 = document.createElement('link');
    cssNode_1.type = 'text/css';
    cssNode_1.rel = 'stylesheet';
    cssNode_1.href = css_path+"window/"+theme+'../window_system.css';
    cssNode_1.media = 'screen';
    headID.appendChild(cssNode_1);
    var cssNode_2 = document.createElement('link');
    cssNode_2.type = 'text/css';
    cssNode_2.rel = 'stylesheet';
    cssNode_2.href = css_path+"window/"+theme+'window.css';
    cssNode_2.media = 'screen';
    headID.appendChild(cssNode_2);
}
