// System global variables

var confirmbox_event;
var to_refresh = false;
var drag_mode = false;

var DropDowns = new Array;

var Editors = new Array;
var ModuleEditors = new Hash;

// End of system vars

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects
   for(var item in arr) {
    var value = arr[item];
   
    if(typeof(value) == 'object') { //If it is an array,
     dumped_text += level_padding + "'" + item + "' ...\n";
     dumped_text += dump(value,level+1);
    } else {
     dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
    }
   }
  } else { //Stings/Chars/Numbers etc.
   dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
} 

function goto_url(url)
{
  window.location.href = url;
}
function load_js(src)
{
  var script = new Element("script", { type: "text/javascript", src: src });
  $$("head")[0].insert(script);
}
function load_module_js(src)
{
  load_js(module_js_url+src);
}
function load_jsfile(src)
{
  load_js(dynamic_js_url+src);
}

function load_jsurl(src)
{
  load_js(src);
}

function enable_drag()
{
  if (drag_mode==false) 
  {
    sortable_init();
    hide_all_modules();
    hide_all_module_options();
    drag_mode=true;
  }
  else
  {
    sortable_close();
    hide_all_modules();
    hide_all_module_options();
    drag_mode=false;
  }
}


function clear_classes(name, set)
{
  elements = document.getElementsByClassName(name);
  for (i=0; i<elements.length; i++) {
    elements[i].className = set;
  }
}
function hide_elements(name)
{
  elements = document.getElementsByClassName(name);
  for (i=0; i<elements.length; i++) {
    elements[i].hide();
  }
}
function show_first_n(name, n)
{
  elements = document.getElementsByClassName(name);
  for (i=0; i<elements.length; i++) {
    if (i<n) elements[i].show();
    else elements[i].hide();
  }
}
/* Calendar */

function load_cal(image, event, input)
{
  if (typeof system_loaded == 'undefined') 
  {
    Event.observe(window, 'load', function() {load_cal(image, event, input)});
    return;
  }
  
  var imgCalendar_Click = function(e, input) {
    showCalendar("calendar", input, "calendar-container", Event.element(e));
  };

  Event.observe(image, event, imgCalendar_Click.bindAsEventListener(this, input));  
}
/*
 * Serves ajax_form requests
 *
 */
function submit_form(container, form_name, _name, _options)
{
  if (_options && _options.indexOf('refresh')) to_refresh = true;
  else refresh = false;
  
  if ($(container)) {
    new Ajax.Updater(container, server_base+'/ajax.php', {
      method: 'post',
      parameters: {
        formbody: Form.serialize(form_name),
        mod_admin: _name,
        opt: _options
      },
      onComplete: function () { 
        if (to_refresh==false) return;
        new Ajax.Updater('page_container', server_base+'/ajax.php', {
        method: 'post',
        parameters: { 
          func: 'refresh' },
        onComplete: function () {
          reinit_all();
        }
        });     
           
       }
    });
  }
  else
  {
    new Ajax.Request(server_base+'/ajax.php', {
      method: 'post',
      parameters: {
        formbody: Form.serialize(form_name),
        mod_admin: _name,
        opt: _options
      },
      onComplete: function () { 
        if (to_refresh==false) return;
        new Ajax.Updater('page_container', server_base+'/ajax.php', {
        method: 'post',
        parameters: { 
          func: 'refresh' },
        onComplete: function () {
          reinit_all();
        }
        });    
       }
    });
  }
}

/*
 * body onkeydown handler for entering admin mode
 *
 */

function keypressHandler (evt)
{
  if (calendar && evt.keyCode == evt.DOM_VK_ESCAPE)
  {
    calendar.closeCalendar();
  }
  if (popup.popup.style.display=="" && evt.keyCode == evt.DOM_VK_ESCAPE)
  {
    popup.hide();
  }
  if (confirm_popup.popup.style.display=="" && evt.keyCode == evt.DOM_VK_ESCAPE)
  {
    Event.stopObserving('confirm_yes_button','click',confirmbox_event.yes_click);
    confirm_popup.hide();
  }
  if (confirm_popup.popup.style.display=="" && evt.keyCode == evt.DOM_VK_RETURN)
  {
    confirmbox_event.yes_click();
  }
  else if (evt.ctrlKey && evt.altKey && evt.keyCode==evt.DOM_VK_E) 
  {
    new Ajax.Request(server_base+'/ajax.php', {
      method: 'post',
      parameters: {
        func: 'adminMode'
      },
      onComplete: function () { 
    
      new Ajax.Updater('page_container', server_base+'/ajax.php', {
      method: 'post',
      parameters: { 
        func: 'refresh' }
      });
      window.location = page_url;
     }
    });
  }
}

function send_data(_module_id, _module_name, _func, _data, _options,  _jsobject)
{
  _jsobject || (_jsobject=null);
  json_data=null;
  if (_jsobject) json_data = _jsobject.toJSON();
  
  new Ajax.Request(server_base+'/ajax.php', {
      method: 'post',
      parameters: {
        mode: 'ajax_data',
        module_id: _module_id,
        module_name: _module_name,
        'function': _func,
        data: _data,
				options : _options,
        JSON: json_data
      }
    });
}

function showEditor2(id, mid)
{
    module_editors = ModuleEditors.get(mid);
    if (typeof module_editors == "undefined") {
        module_editors = new Array();
    }
    module_editors.push(id);
    ModuleEditors.set(mid, module_editors);
    /*
    for(var i=0; i<module_editors.length; i++) {
        alert(module_editors[i]);
    }
    */
    showEditor(id);
}
function showEditor(id, blog) 
{ 
  blog || (blog=0);
  if (Editors.indexOf(id)!=-1) return;
  tinyMCE.execCommand('mceAddControl', false, id);
  Editors.push(id);
  
  if (blog) setTimeout("$('"+blog+"').hide()", 1);
}

function closeEditor(id)
{
  if (Editors.indexOf(id)==-1) return;
  tinyMCE.execCommand('mceRemoveControl', false, id);
  Editors[Editors.indexOf(id)]=null;
}

function hide_w_timeout(id, milisec)
{
    if ($(id)) {
        setTimeout("$('"+id+"').hide()", milisec);
    }
}

/* smarty plugins support */
/*
 * Serves ajax_admin_button requests
 *
 */
function close_admin_module(container, _name)
{
  $(container).innerHTML = "";
  new Ajax.Request(server_base+'/ajax.php', {
    method: 'post',
    parameters: { 
      func: 'close_admin_module',
      opt: '_options' },   // ne postoji _options
    onComplete: function () { 
      
      new Ajax.Updater('page_container', server_base+'/ajax.php', {
      method: 'post',
      evalScripts: true,
      parameters: { 
        func: 'refresh' },
      onComplete: function() {      
        reinit_all();
      }
      });
     // //set_viewport();
     }
  });
}
function load_module(container, _name, _options, onrefresh, _form, refresh_container, _admin, callback, parse_js) 
{  
  parse_js || (parse_js=true);
  
  if (typeof system_loaded == 'undefined') return;
  if (system_loaded==false) return;
  
  close_all();
  if (callback) _callback = callback.toJSON();
  else _callback = null;
  if ($('loading')) $('loading').effect('Appear', 0.3);
  if (_name=='admin_page_edit' && typeof sortable_init == "function")  sortable_init();
  else if (typeof sortable_close == "function") (sortable_close());
  var _formbody;
  if ($(_form)) {
    _formbody = Form.serialize(_form);
  }
  
  if (_options && (_options.indexOf('refresh')>0)) 
  {
    to_refresh = true;
  }
  else to_refresh = false;
    
  new Ajax.Updater(container, server_base+'/ajax.php', {
    method: 'post',
    evalScripts: parse_js,
    parameters: { 
      mod_load: _name,
      opt: _options,
      admin: _admin,
      JSON: _callback,
      formbody: _formbody },
    onComplete: function () { 
      ////set_viewport();  main window scroll
      if (refresh_container=="_window")
      {
        window.location = page_url;
        return;
      }
        
      if (to_refresh==false) {
        if ($('loading')) $('loading').effect('Fade', 0.3);
        eval(onrefresh);
        reinit_all();
        return;
      }
      new Ajax.Updater('page_container', server_base+'/ajax.php', {
      method: 'post',
      evalScripts: parse_js,
      parameters: { 
        func: 'refresh' },
      onComplete: function () { 
        if (_name=='admin_page_edit') {
          load_tiny();
          reinit_edit();
        }
        if ($('loading')) $('loading').effect('Fade', 0.3);
        eval(onrefresh);
        reinit_all();
      }
      });
    }
  });
}

/* Serves ajax_call purposes */

function ajax_admin_call(_options, _form, refresh_container, onrefresh, callback, parse_js)
{
  parse_js || (parse_js=true);
  
  
  if (typeof system_loaded == 'undefined') return;
  if (system_loaded==false) return;
  
  close_all();
  if (callback) _callback = callback.toJSON();
  else _callback = null; 
  
  $('loading').effect('Appear', 0.3);
  var _formbody;
  if ($(_form)) {
    _formbody = Form.serialize(_form);
  }
  
  if ($(refresh_container)) 
  {
    new Ajax.Updater(refresh_container, server_base+'/ajax.php', {
      method: 'post' ,
      evalScripts: parse_js,
      parameters: {
        mod_call: true,
        admin: true,
        opt: _options,
        JSON: _callback,
        formbody: _formbody
      } ,
      onComplete: function () { 
        eval(onrefresh);   
        $('loading').effect('Fade', 0.3);
        if (refresh_container=='system_container')
        {
        reinit_all(); //set_viewport(); main window scroll
        }
      }
    });
  }
  else 
  {  
    new Ajax.Request(server_base+'/ajax.php', {
      method: 'post',
      parameters: { 
        mod_call: true,
        admin: true,
        opt: _options,
        JSON: _callback,
        formbody: _formbody
      } ,
      onComplete: function () { 
        if (refresh_container==false) {
          $('loading').effect('Fade', 0.3); 
          return;
        }
        if (refresh_container=="_window") { 
          window.location = page_url;
          return; 
        }
        if (refresh_container=="_page") { 
          refresh();
          $('loading').effect('Fade', 0.3); 
          return; 
        }
        new Ajax.Updater( refresh_container , server_base+'/ajax.php', {
          method: 'post',
          evalScripts: parse_js,
          parameters: { 
            func: 'refresh' 
          },
          onComplete: function () { 
            eval(onrefresh);
            $('loading').effect('Fade', 0.3);
          }
        } 
        );    
      }
    });
  }
}

function ajax_module_call(_options, _form, refresh_container, onrefresh, callback, parse_js, mid, noscroll)
{
  noscroll = noscroll || false;
  parse_js || (parse_js=true);
  mid || (mid=false);
    
  if (typeof system_loaded == 'undefined') return;
  if (system_loaded==false) return;
  
  close_all();
  if (callback) _callback = callback.toJSON();
  else _callback = null; 
  if ($('loading')) $('loading').effect('Appear', 0.3);
  if (refresh_container=="popup") {
    $('popup_loading').effect('Appear', 0.3);
  }
  else if ($('module_'+mid+'_loading') && refresh_container.indexOf('container_')) $('module_'+mid+'_loading').effect('Appear', 0.3);
  
  var _formbody;
  
  if (_form && $(_form)) {
    _formbody = Form.serialize(_form);
  }
  if ($(refresh_container)) 
  {
    new Ajax.Updater(refresh_container, server_base+'/ajax.php', {
      method: 'post' ,
      evalScripts: parse_js,
      parameters: {
        mod_call: true,
        admin: false,
        opt: _options,
        JSON: _callback,
        formbody: _formbody
      } ,
      onComplete: function () { 
        eval(onrefresh);
        reinit_module();
        if ($('loading')) $('loading').effect('Fade', 0.3);
        
        if (refresh_container=="popup") {
          $('popup_loading').effect('Fade', 0.3);
        }
        else if ($('module_'+mid+'_loading')) {
          $('module_'+mid+'_loading').effect('Fade', 0.3);
        }
        if (!noscroll && refresh_container!="popup") Effect.ScrollTo(refresh_container);
      }
    });
  }
  else 
  {
    new Ajax.Request(server_base+'/ajax.php', {
      method: 'post',
      parameters: { 
        mod_call: true,
        admin: false,
        opt: _options,
        JSON: _callback,
        formbody: _formbody },
      onComplete: function () { 
        if (refresh_container=="_window") { window.location = page_url; return; }   
        if (refresh_container=="_page") { 
          refresh();
          if ($('loading')) $('loading').effect('Fade', 0.3);
          if (refresh_container=="popup") {
            $('popup_loading').effect('Fade', 0.3);
          }
          else if ($('module_'+mid+'_loading')) $('module_'+mid+'_loading').effect('Fade', 0.3);
          return; 
        }     
        if ($('loading')) $('loading').effect('Fade', 0.3);
       }
    });
  }
}

function show_confirm_box(_text)
{
  if (confirmbox_event) Event.stopObserving('confirm_yes_button', 'click', confirmbox_event.yes_click); 
  $('popup_confirm_body').update(_text);
  $('popup_confirm').popup.show();
}

function confirm()
{
  confirmed = true;
}

function ajax_system_call(_func, _options, refresh_container, onrefresh, parse_js)
{
  parse_js || (parse_js=true);
  
  if ($('loading')) $('loading').effect('Appear', 0.3);
  new Ajax.Request(server_base+'/ajax.php', {
    method: 'post',
    parameters: { 
      func: _func,
      opt: _options },
    onComplete: function () { 
      if (refresh_container==false) { eval(onrefresh);$('loading').effect('Fade', 0.3);return; }
      if (refresh_container=="_window") { window.location = page_url; return; }
      if (refresh_container=="_page") { refresh(); $('loading').effect('Fade', 0.3); return; }
      new Ajax.Updater( refresh_container, server_base+'/ajax.php', {
        method: 'post',
        evalScripts: parse_js,
        parameters: { 
          func: 'refresh' 
        }, 
        onComplete: function () { 
          eval(onrefresh);
          if ($('loading')) $('loading').effect('Fade', 0.3);
        }
      });    
    }
  });
}

function set_center_position(element)
{
  var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
      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;
    }
    var el = $(element);
    dim = Element.getDimensions(el);

    x = (windowWidth  - dim.width) / 2;
    y = (windowHeight  - dim.height) / 2;
        
    Element.setStyle(el, { top: y, left: x });
}

/*function set_viewport()
{
  if ($('toolbar')) th = parseInt($('toolbar').getHeight());
  else th = 0;
  $('page_container').style.height = (parseInt(document.body.clientHeight) - th) + "px";
}
*/

function toggle_nav(el)
{
  if ($(el).style.display == "none")
    $(el).effect('BlindDown', 0.3);
  else $(el).effect('BlindUp', 0.3);
}

function repository_toggle_nav(el, path)
{
    data = new Hash();
    data.set('_m_name', 'gallery');
    data.set('function', 'init');
    data.set('path', path)
    data.set('get', 'list_images');
    data.set('show_ajax_box', 2);
    if ($(el).style.display == "none") {
      $(el).effect('BlindDown', 0.3);
      data.set('toggle_nav', 0);
    }
    else {
      $(el).effect('BlindUp', 0.3);
      data.set('toggle_nav', 1);
    }
    ajax_module_call(null, null, '', '', data);
    //ajax_module_call('', '', '', '', data)
    //load_module('', 'admin_repository', '', '', '', '', '', data);
    //ajax_admin_call('', '', '', '', data);
}


function refresh()
{
  new Ajax.Updater('page_container', server_base+'/ajax.php', {
    method: 'post',
    evalScripts: true,
    parameters: { 
      func: 'refresh' },
    onComplete: function () {
      reinit_all();
      load_tiny();
    }
  });     
}

function display_error(where, what, regex, test, equals)
{
  if (equals)
  {
    if ($(regex).value==test)
    { 
      $(where).hide();
    }
    else 
    {
      $(where).innerHTML = what;
      $(where).show();  
    }
    //set_viewport();
  }
  else
  {
    if (regex=="email") 
    regex = /^([+a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    else var regex = new RegExp(regex);
    if (regex.test(test))
    { 
      $(where).hide();
    }
    else 
    {
      $(where).innerHTML = what;
      $(where).show();  
    }
    //set_viewport();
  }
}


function hideModule(id)
{
	if ($('module_content_'+id) && $('module_content_'+id).visible())
	{
		$('module_content_'+id).hide();
		$('icon_up_'+id).show();
		$('icon_down_'+id).hide();
	}
	else if ($('module_content_'+id))
	{
		$('module_content_'+id).show();
		$('icon_up_'+id).hide();
		$('icon_down_'+id).show();
	}
}


/*RESIZE */
// setup the callback function
function onEndCrop( coords, dimensions ) {
	$( 'x1' ).value = coords.x1;
	$( 'y1' ).value = coords.y1;
	$( 'x2' ).value = coords.x2;
	$( 'y2' ).value = coords.y2;
	$( 'width' ).value = dimensions.width;
	$( 'height' ).value = dimensions.height;
}

function display_crop_controls() { 
	new Cropper.Img( 
		'testImage',
		{
			onEndCrop: onEndCrop 
		}
	) 
}

/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
                
function handleEnter(field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
        var i;
        for (i = 0; i < field.form.elements.length; i++)
            if (field == field.form.elements[i])
                break;
        i = (i + 1) % field.form.elements.length;
        field.form.elements[i].focus();
        return false;
    } 
    else
    return true;
}  
function setupZoom() {
    return false;
}
/* tiny mce - load on click - depricated by new version 

function displayTinyMCE (module_id, m_id, m_name, mode, _func, _options)
{

if (mode=="onclick")
{
	tinyMCE.init({
		mode : "exact",
		elements : "inner_"+module_id,
		theme : "advanced",
		theme_advanced_buttons1 : "bold,italic,underline,image,link,unlink,anchor,|,justifyleft,justifycenter,justifyright,|,bullist,numlist",
		theme_advanced_buttons2 : "paste,pasteword,removeformat,|,styleselect,formatselect,|,table,|,code,save,cancel",
		theme_advanced_buttons3 : "",
		plugins : 'advlink,advimage,save,paste,table,contextmenu',
		language : "hr",
		theme_advanced_toolbar_location : "top",
		theme_advanced_resizing : true,

		content_css : "/_design/css/default.css",

	  auto_resize : true,
		save_enablewhendirty : false,
		save_onsavecallback : function(ed) {save_content(module_id, m_id, m_name, _func, _options);}
	});

}
	else
{
		tinyMCE.init({
		mode : "exact",
		elements : "inner_"+module_id
	});
}	
}

function tiny_onchange(inst, value_field) {
	$(value_field).value = inst.getBody().innerHTML;
}


// Pozivanje normalnog tinyMCE editora
function tiny_call(_elements, _mode)
{
	tinyMCE.init({
		mode : "exact",
		elements : _elements,
		theme : _mode,
		theme_advanced_buttons1 : "bold,italic,underline,image,link,unlink,anchor,|,justifyleft,justifycenter,justifyright,|,bullist,numlist",
		theme_advanced_buttons2 : "paste,pasteword,removeformat,|,styleselect,formatselect,|,table,|,code",
		theme_advanced_buttons3 : "",
		plugins : 'advlink,advimage,save,paste,table,contextmenu',
		language : "hr",
		theme_advanced_resizing : true,

		content_css : "/_design/css/default.css",


	});
}

/* saves tinymce contents 

function save_content(module_id, m_id, m_name, _func, _options)
{
  var e = tinyMCE.get("inner_"+module_id, m_id, m_name);
  _html = e.getContent();
  send_data(m_id, m_name, _func, _html, _options);
	tinyMCE.execCommand('mceRemoveControl', false, "inner_"+module_id);
}

function removeMCE(_element)
{
	tinyMCE.execCommand('mceRemoveControl', false, _element);
}


function saveTtxContent (module_id, m_id, m_name, _func, _options)
{
	_html = $('editbox_'+module_id).value; 
	send_data(m_id, m_name, _html, _func, _options)
}
*/


