// -----------------------------------------------------------------------------
// CMS Core JS
// Filip Dostal 2010

// -----------------------------------------------------------------------------
// Operation Output Processing

function process(fields) {
  
  fields += '&submit_method=ajax';
  
  //alert(fields);

  $.ajax({

    type: 'POST',
    url: site_url + '/' + lang_code + '/processor',
    data: fields,
    success: function(data_text) {
      
      // eval JSON object
//      var data = eval('(' + data_text + ')');
      
      try {
        var data = JSON.parse(data_text);
      } catch (e) {
        var data_text_cleaned = data_text.replace(/<br..>/g, '\n');
        data_text_cleaned = data_text_cleaned.replace(/<.*?>/g, ''); 
        alert("Module output error: \n\n" + data_text_cleaned);
        return false;
      }
      
      // clear status bar if present
      if ($('#status_bar').length > 0) $('#status_bar').html("");
      
        //alert('target: ' + data.target + 'redirect ' + data.redirect);

      // retrieve target
      var target
      if (data.target == 0) {
        target = window;
      } if (data.target == 1) {
        target = window.parent;
      }
      
      // retrieve and process redirect
      if (data.redirect == 0) {
      } else if (data.redirect == 1) {
        target.location.reload();
      } else if (data.redirect == 2) {
        target.history.go(-1);      
      } else {
         target.location.href = data.redirect;
      }
      
      // output messages
      if (data.messages != '') {
        if ($(data.messages_target).length > 0) $(data.messages_target).html(data.messages);
      } 
      
    }
    
  });
  
}

function processConfirmed(fields) {
  var answer = confirm("Do you really want to perform this operation?");
  if (answer) process(fields);     
  else return false;
}

// -----------------------------------------------------------------------------

// for cleanup







var window_rel;
var current_tab_uri;
var current_tab;

function tabifyLink(link, tab) {
  var href = $(link).attr('href');
  if (href) {
    var index = href.indexOf('#tab')
    if (index != -1) {
      href = href.substring(0, index); 
    }
    href = href + '#tab=' + tab;
    //alert(href);      
    $(link).attr('href', href);
  }      
}
      

function openWindow(url, rel) {

  url = url + "/param-win"; 
  
  var height = Math.max($(window).height(), $(document).height());
  
  //win.rel = rel;
  window_rel = rel;  
  
  var iframe_height;
  if ($(window).height() < 800) {
    iframe_height = $(window).height() - 100;
  } else {
    iframe_height = 800;
  }  
  
  $(window).resize(function() {
    if ($(window).height() < 800) {
      iframe_height = $(window).height() - 100;
    } else {
      iframe_height = 800;
    }    
    $('#overlay_iframe').height(iframe_height);  
  });
  
  var bg_height = Math.max($(document).height(), $(window).height());
  
  var overlay = '<div id="fader" onclick="closeOverlay();" style="height:' + bg_height + 'px"></div><div id="overlay" onclick="closeOverlay();"><div id="loading">Please wait while the content is loading...</div><iframe id="overlay_iframe" src="' + url + '" style="height:' + iframe_height + 'px;" frameborder="0" ALLOWTRANSPARENCY="true"></iframe></div>';
  
  $("body").append(overlay);

}
    
function closeOverlay() {
    
  $("#overlay").remove();    
  $("#fader").remove();
  $("#loading").remove();

  $(window).resize(function() {      
  });

}
    
function isInIframe() {

  var isInIFrame = (window.location != window.parent.location) ? true : false;
  
  return isInIFrame;

}



function openWindow2(url, rel) {

  win = window.open(url + "/param-win", 'win', 'menubar=0, scrollbars=1, toolbar=0, resizable=1');
  win.rel = rel;
  window_rel = rel;
  
  $(win.document).ready(function() {
    win.resizeTo(1020, $('#content').height() - 20);
    var winl = (screen.width - 1000) / 2;
	  var wint = ((screen.height - $(win.document).height() - 100) / 2);	  
    win.moveTo(winl, wint);    
  });  
  
}








function escapeExpression(str) {
//    return str.replace('\~', "\\$1");
}


function updateParent(value) {

  window.parent.document.getElementById(window.parent.window_rel).value = value;
  var name = window.parent.window_rel.replace(/~/g, '\\~') + "_image";
    
  $.ajax({
    type: 'POST',
    url: site_url + '/cs/feed/get/template=modules/files/feeds/image.php&id=' + value,
    success: function(data) {
      $("#" + name, window.parent.document).html(data);
      window.parent.closeOverlay();
    }
  });    

}

function updateParent2(value) {
  //alert(rel);
  //alert(window.opener.window_rel);
  window.opener.document.getElementById(window.opener.window_rel).value = value;
  
  //$("#image_id~4~opt_image").load('http://www.haniel.cz/cs/feed/get/template=modules/files/files_feed_image.php');
  
  //$("#" + window.opener.window_rel + "_image", window.opener.document).hide();
  
  //$("#test", window.opener.document).html("sss");
  
  //$("#test", window.opener.document).load('http://www.haniel.cz/cs/feed/get/template=modules/files/files_feed_image.php', function() {alert('Load was performed.');});
  
  
  var name = window.opener.window_rel.replace(/~/g, '\\~') + "_image";
  //alert(name);   
    
  $.ajax({
    type: 'POST',
    url: 'http://www.haniel.cz/cs/feed/get/template=modules/files/files_feed_image.php&id=' + value,
    success: function(data) {
      $("#" + name, window.opener.document).html(data);
      window.close();
    }
  });    
    
    
    
  //$("#_" + window.opener.window_rel + "_image", window.opener.document).load('http://www.haniel.cz/cs/feed/get/template=modules/files/files_feed_image.php');

  
  
  
  //window.close();
}

function newWindow(mypage, myname, w, h, scroll, menu, resize, status, toolbar, location) {
	var winl = (screen.width-w)/2;
	var wint = ((screen.height-h)/2);
	var winprops = 'width='+w+',height='+h+',';
	winprops += 'top='+wint+',left='+winl+',';
	winprops += 'scrollbars='+scroll+',';
	winprops += 'menubar='+menu+',';
	winprops += 'resizable='+resize+',';
	winprops += 'status='+status+',';
	winprops += 'toolbar='+toolbar+',';
	winprops += 'location='+location;
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}


function process2(fields) {
  fields += '&submit_method=ajax';
  //alert(fields);
  $.ajax({
    type: 'POST',
    url: site_url + '/' + lang_code + '/processor',
    data: fields,
    success: function(data){
      //var result = data.split("~");
      //$('#status_bar').html("");                    
      //if (result[0] != "") $(result[2]).html(result[0]);           
      
      
      //window.history.go(-1);
      window.location.href = site_url + '/' + return_point;
    }
  });
  return false;
}

function getURLHash(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?#&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.hash );
  if( results == null )
    return "";
  else
    return results[1];
}

$(document).ready(function() {


  //$("#image_id\\~4\\~opt_image").html("sss");
  
  
  
  
  

   function urlencode(s) {
    s = encodeURIComponent(s);
    return s.replace(/~/g,'%7E').replace(/%20/g,'+');
   }
   

  $('.submit').click(function() {
  
    var control = $(this);        
    var form = $('#' + control.attr("rel"));    
    if (form.attr("action") == "" || form.attr("action") == "ajax") {
      var fields = "";
      $(".field", form).each(function () {
          if ($(this).attr("type") == "checkbox") {
            if ($(this).attr("checked")) fields += $(this).attr("name") + "=on" + "&";
            else fields += $(this).attr("name") + "=off" + "&";            
          } else {      
            encoded_value = $(this).val();
            fields += $(this).attr("name") + "=" + encodeURIComponent(encoded_value) + "&";
          }      
      });
      //alert(fields);
      $('#status_bar').html("Processing...");
      process(fields);      
    } else {
      form.attr("action", site_url + '/' + lang_code + '/processor/tab=' + current_tab + '&');
      form.attr("method", "POST");
      form.attr("enctype", "multipart/form-data");
      //alert("reg submit");
      form.submit();    
    }
    return false;
  });


    
    $(".datepicker").datepicker({ dateFormat: date_format, firstDay: 1, prevText: '«', nextText: '»'});
    

    
      $('.upload_bypass').val("");
      
      $('.ajaxupload').each(function() {
        //alert("test");
        var ajaxupload = $(this);
        var button = $('.btn', ajaxupload); 
      	new AjaxUpload(button, {
      	  name: 'upload',
      		action: site_url + '/' + lang_code + '/processor',
      		data: {
      		  source: "files",
      		  operation: "upload"
          },
      		onSubmit : function(file, response) {
      		  $('#status_bar').html("Uploading file " + file + "...");      		  
      		},        
      		onComplete : function(file, response) {
      		  $('#status_bar').html("");      		  
      		  //$('#status_bar').html("File " + file + " uploaded successfully.");
      		  var result = response.split("~");
      			$('#upload', ajaxupload).val(result[0]);
      			$('.upload_bypass', ajaxupload).val(result[1]);
      			$('#upload_ext', ajaxupload).val(result[2]);
      			$('#upload_size', ajaxupload).val(result[3]);
      			$('#upload_type', ajaxupload).val(result[4]);
      		}	
      	});    
    	});

            
      var tab_on_load = getURLHash("tab");
      if (tab_on_load == "") tab_on_load = "tab0";
      current_tab_uri = "#tab=" + tab_on_load;
      current_tab = tab_on_load;            

      var i = 0; 
      $('.tabs_controls a').each(function() {
        var tabs = $(this).parent().parent();
        var tab = $(this);
        if (tab_on_load == tab.attr("rel")) {
          tab.addClass("current");
        } else {
          $('#' + tab.attr("rel"), tabs).hide();
         }        
        //alert(tabs.attr("id"));
        $(this).click(function() {
          window.location.replace("#tab=" + tab.attr("rel"));
          $('.tabs_controls a', tabs).removeClass("current");
          tab.addClass("current");
          $('.tabs_tab', tabs).hide();
          $('#' + tab.attr("rel"), tabs).show();
          current_tab_uri = "#tab=" + tab.attr("rel");
          current_tab = tab.attr("rel");
          $('.pagination a').each(function() {
            tabifyLink($(this), tab.attr("rel"));
          });
          $('#filter_all').each(function() {
            tabifyLink($(this), tab.attr("rel"));
          });          
        });
        i++;
      });
      
      if (tab_on_load) {
        $('.pagination a').each(function() {
          tabifyLink($(this), tab_on_load);
        });
        $('#filter_all').each(function() {
          tabifyLink($(this), tab_on_load);
        });     
      }

});



function processx(fields) {      // deprecated
  fields += '&submit_method=ajax';
  //alert(fields);
  //alert(site_url + '/' + lang_code + '/processor');
  $.ajax({
    type: 'POST',
    url: site_url + '/' + lang_code + '/processor',
    data: fields,
    success: function(data){
      //alert(data);
      var result = data.split("~");
      $('#status_bar').html("");  
                        
      if (result[0] != "") $(result[3]).html(result[0]);
      
      //alert("result1" + result[1]);
                
      if (result[1] == "2") {
        window.history.go(-1);
      } else if (result[1] == "1") {
        if (result[2] == 1) window.parent.location.reload();
        else window.location.reload();        
      } else if (result[1] == "3") {
        window.parent.location.reload();
      } else if (result.length > 1) {
        //alert("OK");
        if (result[1] != "0") {
          if (result[2] == 1) window.parent.location.href = result[1];
          else window.location.href = result[1];
        }
      } else {
        //alert('error');
        //alert(data);
      }
    }
  });
}

