var EDITMODE = true;
var EDITMODE = true;
var submit_was_called = false;
var grid_div_delete_confirmation_string = '';
var grid_new_divs_id = 0;
var optimized_h_ = 0.8;
var optimized_w_ = 0.8;
var scrolled = 0;

var PIPE_SEPARATOR 		= '~^_pipe_^~';
var COLON_SEPARATOR 		= '~^_colon_^~';
var SEMICOLON_SEPARATOR 	= '~^_semicolon_^~';
var EQUAL_SEPARATOR 		= '~^_equal_^~';
(function($) {
    $.fn.countdown = function(year, month, day, hour, minute, second)
    {
        Today = new Date();
        Todays_Year  = Today.getFullYear() - 2000;
        Todays_Month = Today.getMonth() + 1;
        /*Convert both today's date and the target date into miliseconds.*/
        Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(), Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
        Target_Date = (new Date(year, month, day, hour, minute, second)).getTime();
        /*Find their difference, and convert that into seconds.*/
        Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
        if (Time_Left < 0) {
            Time_Left = 0;
        }
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        Time_Left %= 60;
        seconds = Time_Left;
        if (seconds < 10) {
            seconds = '0' + seconds;
        }
        $(this).html(((hours > 0) ? (hours   + ':') : '') + minutes + ':' + seconds);
        if (hours == '0' && minutes == '00' && seconds == '00') {
            clearTimeout();
        }
        var self = this;
        /*Recursive call, keeps the clock ticking.*/
        setTimeout(function(){self.countdown(year, month, day, hour, minute, second);}, 1000);
    };
    $.fn.highlightRows = function()
    {
        $(this).find('tr').hover(
        function() {
            $(this).addClass('listover');
        }, function() {
            $(this).removeClass('listover');
        }
        ).click(
        function() {
            $(this).find(':radio').attr('checked', 'checked').end().addClass('selected').siblings('.selected').removeClass('selected');

            if ( $(this).find(':checkbox').size()) {           
            	checkbox = $(this).find(':checkbox');
            	if (checkbox.attr('checked')) {
            		checkbox.attr('checked', '');
            	} else {
            		checkbox.attr('checked', 'checked');
            	}
            	checkbox.addClass('selected').siblings('.selected').removeClass('selected');
            };

        }
        ).filter(':even').addClass('panel_wb_even');
    };

    $.fn.highlight = function()
    {
        $(this)
        .find('.row')
        .hover(
            function() {
                $(this).addClass('listover');
            },
            function() {
                $(this).removeClass('listover');
            }
        )
        .filter(':even')
        .addClass('panel_wb_even');
    };
    $.fn.selectRow = function (nr)
    {
        if (nr) {
            $(this).find("tr:has(td):has(input[type=radio][value="+nr+"])").click();
            $(this).find(":input[type=radio][value="+nr+"]").click();
        } else {
            $(this).find("tr:has(td):eq(0)").click();
            $(this).find(":input[type=radio]:eq(0)").click();
        }
    };
    $.fn.selectCell = function (product, type)
    {
		if ($('#selection_'+product+'_'+type).val() == 0) {
			$(this).parent().parent().find("input[type=hidden][id^=selection_"+product+"_]").val(0);
			$(this).parent().parent().find("td[id^="+product+"_]").removeClass('listover');
			$('#'+product+'_'+type).addClass('listover');
			$('#selection_'+product+'_'+type).val(1);
		} else {
			$('#'+product+'_'+type).removeClass('listover');
			$('#selection_'+product+'_'+type).val(0);
		}
		
		sum = 0;
		$(this).parent().parent().find("input[type=hidden][id^=selection_][value=1]").each(function(){sum = parseInt(sum) + parseInt(this.title);});		
		$('#total').html(parseInt(sum)+parseInt($('#total_hidden_2').val()));
		$('#total_next').html((parseInt(sum)+parseInt($('#total_hidden_2').val()))*0.25);
		$('#total_hidden').val(sum);
    };	
    $.fn.checkSelectedRadio = function (msg)
    {
        if ($('#form').find(":radio").size() && !$('#form').find(":radio:checked").size()) {
            submit_was_called = false;
            return false;
        } else {
            return true;
        }
    };
    $.fn.check = function (checkbox)
    {
      if (!$(this).attr('checked')) {
        $(this).attr('checked', 'checked');
      } else {
        $(this).removeAttr('checked');
      }
    };
    $.fn.submitform = function (formname, pressbutton, action, checkonsubmit, msg)
    {
        if (!submit_was_called) {
            /* check if there is a form to submit */
            if (!$('#'+formname).is('form')) {
                return true;
            }
            /*remeber that form was submited*/
            submit_was_called = true;
            if (action) {
                $('#'+formname).attr("action", action);
            }
            $("input:hidden[name='task']", document.body).val(pressbutton);
            if (checkonsubmit) {
                $('#'+formname).submit(function() {
                    return $('#'+formname).checkSelectedRadio(msg);
                });
            }
            $('#'+formname).submit();
            return false;
        } else {
            /* form was submited - do nothing*/
            return false;
        }
    };

    /* disable and enable forma action buttons depending on choosen node (user or group)*/
    $.fn.activateSiteMapTreeFunctions = function (id,type,has_children,has_grid,visible)
    {
        e  = $('#form_action_enable');
        d  = $('#form_action_disable');
        iv = $('#form_action_view');
        ie = $('#form_action_edit');
        el = $('#form_action_edit_link');
        dl = $('#form_action_delete_link');
        ep = $('#form_action_edit_page');
        eg = $('#form_action_edit_grid');
        dp = $('#form_action_delete_page');
        if (type == 'page') {
            /* off */
            if (el.size()) el.hide();
            if (dl.size()) dl.hide();
            /* on */
            if (ep.size()) ep.show();
            if (iv.size()) iv.show();
            if (ie.size()) ie.show();
            if (dp.size() && !has_children) {
                if (dp.size()) dp.show();
            } else {
                if (dp.size()) dp.hide();
            }
        } else {
            /* link */
            /* on */
            if (el.size()) el.show();
            if (dl.size() && !has_children) {
                if (dl.size()) dl.show();
            } else {
                if (dl.size()) dl.hide();
            }
            /* off */
            if (ep.size()) ep.hide();
            if (dp.size()) dp.hide();
            if (iv.size()) iv.hide();
            if (ie.size()) ie.hide();
        }
        if (id == '1') {
            if (ep.size()) ep.hide();
            if (dp.size()) dp.hide();
            if (el.size()) el.hide();
            if (dl.size()) dl.hide();
            if (iv.size()) iv.hide();
            if (ie.size()) ie.hide();
            if (d.size())  d.hide();
            if (e.size())  e.hide();
        }
        if (eg.size() && has_grid) {
            if (eg.size()) eg.show();
        } else {
            if (eg.size()) eg.hide();
        }
        if (id != '1') {
            if (d.size()) d.showOrHide(visible);
            if (e.size()) e.showOrHide(!visible);
        }
    };
    /* disable and enable forma action buttons depending on choosen node (user or group)*/
    $.fn.hideEnableAndDisableActionButtons = function (visible)
    {
        $('#form_action_enable').showOrHide(!visible);
        $('#form_action_disable').showOrHide(visible);
    };
    $.fn.switchPreviewAndEditMode = function ()
    {
        if (typeof EDITMODE == "undefined") {
            EDITMODE = true;
        }
        if (EDITMODE) {
            EDITMODE = false;
        } else {
            EDITMODE = true;
        }
        $('#form_action_view').showOrHide(EDITMODE);
        $('#form_action_edit').showOrHide(!EDITMODE);
        $('#form_action_edit_grid').showOrHide(!EDITMODE);
        $('.flash').showOrHide(!EDITMODE);
        $('.flash_info').showOrHide(EDITMODE);
        $(this).enableDisableGridButton(0, '');
        return false;
    };
    $.fn.enableDisableGridButton = function (ENABLE, grid_background)
    {
        $('#form_action_add_link, #form_action_add_imagelink,#form_action_add_flash, #form_action_add_text, #form_action_add_content, #form_action_add_textarea, #form_action_add_image, #form_action_add_colorbar, #form_action_increse, #form_action_decrese, #form_action_apply, #form_action_save, #form_action_save_as, #form_action_cancel_grid, #form_action_add_plugin').showOrHide(ENABLE);
        if (ENABLE && $('#grid').size()) {
            $('#grid').css('background', 'url('+grid_background+') repeat');
        }
    };
    $.fn.showOrHide = function(show)
    {
        show ? $(this).show() : $(this).hide();
    };


    $.fn.switchPreviewAndEditGridMode = function(deleteConfirm, grid_background)
    {
        $(this).enableDisableGridButton(true, grid_background);
        $('#form_action_view, #form_action_edit, #form_action_edit_grid, #form_action_cancel, .flash').hide();
        $('#panel_header, .panel_menu_bottom').css('z-index', '99999');
        $('#grid').initGrid(deleteConfirm);
        return false;
    };
    $.fn.initGrid = function(txt)
    {
        grid_div_delete_confirmation_string = txt;
        $(this).children().filter('div').each(function(){$(this).makeEditable()});
    };
    $.fn.saveGrid = function()
    {
        var str = '';
        grid_        = $('#grid');
        grid_offset_ = grid_.offset();
        str          = str + COLON_SEPARATOR + 'Grid' + COLON_SEPARATOR + grid_.width() + COLON_SEPARATOR + grid_.height() + COLON_SEPARATOR + grid_offset_.top + COLON_SEPARATOR + grid_offset_.left + PIPE_SEPARATOR;
        grid_.children().filter('div').each(function(){
            o       = $(this);
            offset_ = o.position();
            inst_   = o.attr('title');
            inst_   = (typeof inst_ != 'undefined') ? inst_ : '';
            type_   = o.attr('id');
            type_   = type_.split('_');
            type_   = type_[0];
            str     = str + inst_ + COLON_SEPARATOR + type_ + COLON_SEPARATOR + o.width() + COLON_SEPARATOR + o.height() + COLON_SEPARATOR + offset_.top + COLON_SEPARATOR + offset_.left + PIPE_SEPARATOR;
        });
        $('#gridcomposition').val(str);
        return true;
    };
    $.fn.resizeGrid = function()
    {
        max_ = 0;
        grid_offset_ = $(this).offset();
        $(this).children().filter('div').each(function(){
            offset_ = $(this).offset();
            m_      = offset_.top + $(this).height();
            max_    = (max_ >= m_) ? max_ : m_;
        });
        $(this).height(max_ - grid_offset_.top);
    };
    $.fn.increaseGrid = function(px)
    {
        $(this).height($(this).height() + px);
    };
    $.fn.decreaseGrid = function(px)
    {
        $(this).height($(this).height() - px);
    };
    $.fn.makeEditable = function()
    {
        if ($(this).size()) {
            type_   = $(this).attr('id');
            type_   = type_.split('_');
            type_   = type_[0];
        } else {
            return false;
        }
        $(this)
        .css({'background': 'url('+_HTTP_PATH+'view/gfx/add_'+type_.toLowerCase()+'_grid.gif)', cursor: 'move'})
        .addClass('ui-wrapper')
        .resizable({autohide: true, containment: 'parent',
        start: function(e, ui) {
            $(this).prepend('<span class="resized_position" style="position:absolute; height:16px; text-align: center; left:0; right: 6px;background: red; color:white; z-index:1">X</span>');
        },
        resize: function(e, ui) {
            $(this).css({opacity: 0.6});
            $(this).find('.resized_position').html($(this).width() +'x'+ $(this).height());
        },
        stop: function(e, ui) {
            $(this).css({opacity: 1});
            $(this).find('.resized_position').remove();
        }
        })
        .draggable({containment: 'parent',
        start: function(e, ui) {
            $(this).prepend('<span class="dragged_position" style="position:absolute; height:16px; text-align: center; left:0; right: 6px;background: red; color:white; z-index:1">X</span>');
        },
        drag: function(e, ui) {
            $(this).css({opacity: 0.6});
            parent_window  = $(this).parent().offset();
            dragged_window = $(this).offset();
            $(this).find('.dragged_position').html((dragged_window.left - parent_window.left) +'x'+ (dragged_window.top - parent_window.top));
        },
        stop: function(e, ui) {
            $(this).css({opacity: 1});
            $(this).find('.dragged_position').remove();
        }
        })
        .prepend('<span style="position:absolute; width: 16px; height:16px; text-align: center; top:0; right: 6px;cursor: pointer; font-weight:bold;background: red; color:white; z-index:1" onclick="if (confirm(\''+grid_div_delete_confirmation_string+'\')) $(this).deleteNode();">X</span>')
        .find('a')
        .click(function(){return false;})
        .css({cursor: 'move'});
        //.end().find('p').css({display: 'inline'});
    };
    $.fn.addNode = function (type)
    {
        $('#grid').append('<div id="'+type+'_f'+ grid_new_divs_id +'" style="width: 100px; height: 100px; background: #eee; position: absolute;z-index: '+grid_new_divs_id+'; top: 0; left:0; overflow: hidden"></div>')
        .children().filter('#'+type+'_f'+ grid_new_divs_id).makeEditable();
        grid_new_divs_id++;
    };
    $.fn.deleteNode = function ()
    {
        $(this).parent().remove();
    };
    $.fn.runEditor = function (page, sender, instanceClass)
    {
        /*there is no way to upload files via ajax request (security stuff)
        * so components with fieles upload must be handled without ajax*/
        runAjaxSave = (instanceClass == 'ImageComponent' || instanceClass == 'ImageLinkComponent') ? 'image' : 0;
        runAjaxSave = (instanceClass == 'FlashComponent') ? 'flash' : 0;
        runAjaxSave = (instanceClass == 'TextAreaComponent') ? 'textarea' : runAjaxSave;
        $(this).createEditDiv();
        $(this).getEditForm(page, sender, runAjaxSave);
    };
    $.fn.createEditDiv = function ()
    {
        $('body').append('<div id="grid_overlay_ajax" class="grid_overlay grid_overlayBG" />');
        scrolled = $(window).scrollTop();
        $(window).scrollTop(0);
        $('html, body').css('overflow', 'hidden');

        $('#panel_body').createWindow('grid_window', $(window).width() * optimized_w_, $(window).height() * optimized_h_);
    };
    $.fn.saveEditForm = function()
    {
        var options = {
            target: '#'+$(this).attr('id'),
            success: function() {
                $(this).cancelAjaxEditBox();
            }
        };
        $('#form').submit(function(){
            if (window.onSubmitAction) {
                onSubmitAction();
            }
            $(this).ajaxSubmit(options);
            return false;
        });
    };
    $.fn.getEditForm = function (page, sender, runAjaxSave)
    {
        handler = $(this);
        $.ajax({
            type: "GET",
            url: "index.php",
            data: "m=Html&a=edit&output=ajax&page="+page+"&sender="+sender,
            beforeSend: function () {
                $('#grid_window_content').append('<img id="ajax_loader" src="'+_HTTP_PATH+'view/gfx/ajax-loader.gif" alt="Loading" style="top:50%;left:50%; margin-left:-50px;margin-top:-50px; border:none; position:absolute;" />');
            },
            success: function(html) {
                $('#grid_window_content').append(html);
                $('#ajax_loader').remove();
                if (runAjaxSave == 'textarea') {
                    $(this).tinyinit(handler.width()+16, handler.height()+39);
                }
                if (runAjaxSave != 'image' && runAjaxSave != 'flash') {
                    handler.saveEditForm();
                }
            }
        });
    };
    $.fn.browseImages = function ()
    {
        $(this).createBrowseDiv();
        $.ajax({
            type: "GET",
            url: "index.php",
            data: "m=Html&a=browse_images&output=ajax",
            dataType: 'html',
            beforeSend: function () {
                $('#grid_window').hide();
                $('#browse_window_content').append('<img id="ajax_loader" src="'+_HTTP_PATH+'view/gfx/ajax-loader.gif" alt="Loading" style="top:50%;left:50%; margin-left:-50px;margin-top:-50px; border:none; position: absolute;" />');
            },
            success: function(html) {
                $('#ajax_loader').remove();
                $('#browse_window_content').append(html).show();

                $("#browseImages").css({overflow: 'auto'}).find('a').click(function(){
                    w_ = $(this).attr('width_');
                    h_ = $(this).attr('height_');

                    if (!$('#grid_overlay_images').size()) {
                        //$('#browseImages').createPrepend('div', {id: "grid_overlay_images", className: 'grid_overlay grid_overlayBG'});
                        $('#browseImages').prepend('<div id="grid_overlay_images" class="grid_overlay grid_overlayBG" />');
                        $('#grid_overlay_images').css({height: $('#browseImages').height()});
                    }

                    $('#panel_body').createWindow('image_window', $(window).width() * optimized_w_, $(window).height() * optimized_h_);
                    $('#image_window_content')
                    .html('<img id="image_ajax_loader" src="'+_HTTP_PATH+'view/gfx/ajax-loader.gif" alt="Loading" style="top:50%;left:50%; margin-left:-50px;margin-top:-50px; border:none; position: absolute;" />')
                    .append('<div id="large"><img id="source" src="" title="" alt="" /><div id="large_icons" class="panel_menu_bottom_ajax"><ul><li><a href="#" id="cancel"><img  src="'+_HTTP_PATH+'view/gfx/cancel.gif" title="" alt="" /></a></li><li><a href="#" id="apply"><img src="'+_HTTP_PATH+'view/gfx/apply.gif" title="apply" alt="apply" /></a></li></ul></div></div>');

                    $('#image_window').css({overflow: 'auto'}).show();
                    $('#image_ajax_loader').show();

                    $('#large')
                    .show()
                    .find('#source')
                    .attr({"src": $(this).attr("href")})
                    .css({position: 'static', margin: 0})
                    .click(function(){
                        $('#grid_overlay_images').remove();
                        $('#image_window').remove();
                        $('#large_icons').hide();
                    })
                    .load(function(){
                        $('#image_ajax_loader').hide();
                        $('#large_icons').show();
                    });

                    if (w_ < $(window).width() * optimized_w_ || h_ < $(window).height() * optimized_h_) {
                        $('#source').css({
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            'margin-left': (w_/-2),
                            'margin-top': (h_/-2)
                        });
                    }

                    $('#cancel').css('cursor', 'pointer').click(function(){
                        $('#source').click();
                    });
                    $('#apply').css('cursor', 'pointer').click(function(){
                        $('#properties_src').val($('#source').attr('src'));
                        $('#previewImage img').attr('src', $('#source').attr('src')).width($('#properties_width').val()).height($('#properties_height').val());
                        $('#source').click();
                        $(this).cancelBrowseImages();
                    });

                    return false;
                });

            }
        });
    };
    $.fn.createBrowseDiv = function ()
    {
        $('#panel_body').createWindow('browse_window', $(window).width() * optimized_w_, $(window).height() * optimized_h_);
    };
    $.fn.createWindow = function(id_, w_, h_)
    {
        scroll_ = 0;
        if ($.browser.msie && $.browser.version == 6.0) {
            scroll_ = $(document).scrollTop();
        }
        $(this).append('<div id="'+id_+'" class="thickbox_window" style="margin-left: '+(w_/-2)+'px; width: '+w_+'px; height:'+h_+'px; margin-top: '+(h_/-2-19+scroll_)+'px; display: block; overflow-y: auto"><div id="'+id_+'_content" style="width:'+(w_-16)+'px; height: 100%;"></div></div>');
        $(window).resize(function(){
            if ($('#'+id_).size()) {
                scroll_ = 0;
                if ($.browser.msie && $.browser.version == 6.0) {
                    scroll_ = $(document).scrollTop();
                }
                w_ = $(window).width() * optimized_w_;
                h_ = $(window).height() * optimized_h_;
                $('#'+id_).width(w_);
                $('#'+id_).height(h_);
                $('#'+id_).css('margin-left', w_/-2);
                $('#'+id_).css('margin-top', h_/-2-19+scroll_);
            }
        });
    };
    $.fn.cancelBrowseImages = function()
    {
        $('#browse_window').remove();
        $('#grid_overlay_ajax').css('opacity', '0.75');
        $('#grid_window').show();
    };
    $.fn.cancelAjaxEditBox = function()
    {   
        $('html, body').css('overflow', 'auto');
        $(window).scrollTop(scrolled);
        $('#grid_window, #image_window, #grid_overlay_ajax').remove();
        submit_was_called = false;
        return false;
    };
    /*$.fn.turnOnEditor = function ()
    {
        $('#mce_editor_0_toolbar').show();
    };*/
    $.fn.tinyinit = function (width, height)
    {
      
        $('#textareaEdit').tinymce({
            // Location of TinyMCE script
            //script_url : '../js/tinymce/jscripts/tiny_mce/tiny_mce.js',
            width: width,
            height: height,
            language : "en",
            strict_loading_mode: true,
            mode : "exact",
            convert_urls: false,
            elements : 'textareaEdit',
            theme : "advanced",
            theme_advanced_buttons1 : "selectall,bold,italic,underline,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,outdent,indent,cut,copy,paste,undo,redo,link,unlink,image,cleanup,help,code,hr,removeformat,formatselect,fontselect,fontsizeselect,styleselect,sub,sup,forecolor,backcolor,charmap,visualaid,anchor,newdocument,separator",
            //theme_advanced_buttons1 : "selectall",
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            theme_advanced_disable : "hr,cut,copy,paste,image,help,formatselect,fontselect,fontsizeselect,styleselect,forecolor,backcolor,visualaid,newdocument,separator",
            //theme_advanced_toolbar_location : "top",
            theme_advanced_toolbar_location : "external",
            theme_advanced_toolbar_align : "left",                       
            theme_advanced_statusbar_location : "none",
            
            content_css : "view/css/webpage.css",
            theme_advanced_buttons1_add : "advhr",
            theme_advanced_buttons1_add_before : "selectall",
            plugins : "contextmenu,advhr,advlink,paste"
        });
    };
    
    $.fn.toggleEditor = function(id) {
      if (!tinyMCE.get(id))
        tinyMCE.execCommand('mceAddControl', false, id);
      else
        tinyMCE.execCommand('mceRemoveControl', false, id);
    };
    $.fn.publish =  function()
    {
        $.ajax({
            type: "GET",
            url: "index.php",
            data: "m=Publish&a=publish",
            success: function(html) {
                if ($.trim(html) != 'PUBLISH_END') {
                    counts_ = html.split('|');
                    all_    = counts_[0];
                    curr_   = counts_[1];
                    $('#progressbar').width(((486 / all_) * curr_));
                    $('#all_pages_to_publish').text(all_);
                    $('#already_published_pages').text(curr_);
                    $(this).publish();
                } else {
                    window.location.href = 'index.php?m=Publish&a=publish&end=1';
                }
            }
        });
    };
    $.fn.assignLoadedImage = function(loadedImage)
    {
        submit_was_called = false;
        if (loadedImage) {
            li = $(loadedImage).children().filter('img');
            if (!li.size()) {
                li = $(loadedImage);
            }
            $('div[@title=id_'+li.attr('id')+']')
            .html(loadedImage)
            .css({
                width: li.attr('width'),
                height: li.attr('height')
            });
            $(this).cancelAjaxEditBox();
        }
    };

    /*
    $.fn.assignLoadedImage = function(loadedImage)
    {
        submit_was_called = false;
        $(this).cancelAjaxEditBox();
        $('.flash').hide();
    };
    */

    $.fn.switchHeight = function()
    {
        $(this).click(function(){
            if ($(this).attr('checked')) {
                $("#old_height").val($("#height").val());
                $("#height").val('').hide();
            } else {
                $("#height").val($("#old_height").val()).show().focus();
            }
        });
    }
    
    $.fn.makeSortable = function()
    {   
        $(this).sortable({
          update: function(){
            var sort = '';
            $(this).find('li').each(function(){
              sort = sort + $(this).attr('id').substr(3) + ',';
            })
            $('#sort').val(sort);
          }, axis: 'y', containment: 'parent', cursor: 'pointer'
        });        
    }    

})(jQuery);

