var dialogRef;



function UpdateDialog(dialog,param,reopen,formId) {
  if(!(reopen === undefined) && reopen == 'true') {
    CloseDialog();  
  }
  
  var formData = "";
  if(formId === "undefined") {
  } else {
    formData = $("form#" + formId).serialize();
    formData += "&";
  }
  
  param = formData + param;
  param = escape(param);
  
  ShowDialog(dialog,param);
}

         
function CloseDialog() {
  $(dialogRef).dialog("destroy").remove();
}
          

function ExecScript(scriptName,formId,param,conf) {
  
  if(conf === undefined) {
    conf = "";
  }
  
  if(conf != "") {
    var odpoved = confirm(conf);
  	
  	if(!odpoved) {
  		return false;
  	}
  }
  
	var formData = "";
	if(formId != "") {
		formData = $("form#" + formId).serialize();
		formData += "&";
	}
	
	var p = "__ajax__=true&" + formData + param;
	
	
	$.ajax(
	{
	    type: "POST",
	    url: "/script/" + scriptName,
	    data: p,
		  success: function(msg) {
		  
			JsonCallback(msg,"");
		}
	}
  )	
}




/*
function UpdateWidgetCallback(widgetName,params,func) {
	var p = $("form.update").serialize();
	if(p != "") {
		p += "&";
	}
	
	p += "__ajax__=true&" + params;

	$.ajax(
	{
	    type: "POST",
	    url: "/ajax/widget/" + widgetName,
	    data: p,
	    success: function(msg) {
			JsonCallback(msg,func);
	    }
	}
  )  
}
*/

var ifr = false;
function UploadImage(formId) {

  if($("#" + formId + " input#keywords").val()==""){
    alert('Nie sú zadané kľúčové slová.');
    return false;
  };

  if($("#" + formId + " input#zdroj").val()==""){
    alert('Nie je zadaný zdroj.');
    return false;
  };  
  
  if($("#" + formId + " input#popis").val()==""){
    alert('Nie je zadaný popis.');
    return false;
  };
  
  $("#" + formId).attr("target","ifr");

  if(!ifr) {
    var iframe = '<iframe style="display: none;" id="ifr" onload="UploadCallback()" name="ifr"><html><body></body></html></iframe>';
    $('body').append(iframe);
    ifr = true;
  }
}

function UploadCallback() {
  var data = $("#ifr").contents().find("html body").html();  
  $("#ifr").contents().find("html body").html("");
  JsonCallback(data,"");
}



function JsonCallback(jsonstring,func) {
   // alert(jsonstring);
	json = JSON.parse(jsonstring);
  

	if(json.updatevalue == true) {
		var num = json.values.length;
		for(var i=0;i<num;i++) {
			w = json.values[i];
			$("form#" + w[0] + " " + "input#" + w[1]).attr("value",w[2]);
		}
	}
	
	
	if(json.update == true) {
		var num = json.widgets.length;
		for(var i=0;i<num;i++) {
			w = json.widgets[i];
			
			
			$(w[0]).html(w[1]);
		}
	}
	
	if(json.updateelement == true) {
    $("#" + json.updateelementid).html(json.updateelementhtml);
  }
	
	if(json.closedialog == true) {
		CloseDialog();
	}
	
	if(json.redirect == true) {
		window.location = json.url;
	}
	
	if(json.replace == true) {
		$("#" + json.replacetarget).html(json.replacecontent);
	}
	
	if(json.nextdialog != "") {
		CloseDialog();	
		ShowDialog(json.nextdialog,json.nextdialogparam);
  }
	
	if(json.updatewidget != "") {
		UpdateWidget(json.updatewidget,json.updateparam);
	}
	
	if(json.msg == true) {
		if(json.msgtarget != "") {
			$("#" + json.msgtarget).html(json.msgcontent);
		}
		else {
			alert(json.msgcontent);
		}
	}
	
	if(json.dialog == true) {	
	 if(dialogRef === undefined) {
		$('body').prepend('<div class="dialog" id="_dialog"></div>');
		dialogRef = $("#_dialog");
	 } else {
    CloseDialog();
   }
		$(dialogRef).dialog(
		{
			width: json.dialogwidth,
			height: json.dialogheight,
			resizable: json.dialogresizable,
			draggable: true,
			title:json.dialogtitle,
			modal:true,
			close:function(e,u){
				CloseDialog();
		  }
		}
		);
	
		$(dialogRef).html(json.dialogcontent);
	}
	
	if(func != "") {
    func();
  }
	
	return json.returnCode;

}


function SelectImage(imageId) {
	var target = $("input#target").attr("value");
	if(target != "undefined") {
		$("#" + target).attr("value",imageId);
		UpdateWidget('PicturePreview','obrazok_id=' + imageId);
	}
}

function Potvrd() {
	var odpoved = confirm("Naozaj chcete odstrániť túto položku?");
	
	if(odpoved) {
		return true;
	}
	
	return false;
	
}
function addToFavorites()
{
 var url = "http://www.ovolbach.sk";
 var title = "O Voľbách";
 if (document.all)
 {
 window.external.AddFavorite(url, title);
 return false;
 }
 else if (window.sidebar)
 {
 window.sidebar.addPanel( title, url, "");
 return false;
 }
 else if(window.opera && window.print)
 {
 return true;
 }
 else
 {
 alert("Prepáčte ale Váš prehliadač nepodporuje túto funkciu");
 return false;
 }
}

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}






/**
 * find all selected comments in the table with comments and send delete request
 */
function deleteSelectedComments( table ) {
	var selectedComments = $("input[type='checkbox']:checked",table).map( function() {
			return $(this).val(); 
		} ).get().join('-');

	if( confirm( "Zmazať vybrané komentáre?" ) ) {
		ExecScript('deletecomments','','selected_comments='+selectedComments);	
	}

	return false;
}


/**
 * select all comments
 */
function selectAllComments( table ) {
	$("input[type='checkbox']",table).attr('checked', true);
}

/**
 * invert the selection of comments
 */
function invertSelectedComments( table ) {
	$("input[type='checkbox']",table).each( function() {
		if( $(this).is(':checked') ) {
			$(this).attr('checked', false);
		} else {
			$(this).attr('checked', true);
		}
	} );
}

/**
 * replace the nadavka form submit behavior with sending Ajax request
 */
function initNadavkaForm() {
	$(document).ready( function() {
		$("#nadavka-form").submit( function() {
			ExecScript('addnadavka', 'nadavka-form', '' );

			return false;
		} );
	} );
}


/**
 * replace the nadavka detail form submit behavior with sending Ajax request
 */
function initNadavkaDetailForm() {
	$(document).ready( function() {
		$("#nadavka-detail-form").submit( function() {
			ExecScript('updatenadavka', 'nadavka-detail-form', '' );

			return false;
		} );
	} );
}


// http://www.texotela.co.uk/code/jquery/numeric/
// numeric edit box ...
jQuery.fn.numeric = function(decimal, callback)
{
decimal = decimal || ".";
callback = typeof callback == "function" ? callback : function(){};
this.keypress(
function(e)
{
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
// allow enter/return key (only when in an input box)
if(key == 13 && this.nodeName.toLowerCase() == "input")
{
return true;
}
else if(key == 13)
{
return false;
}
var allow = false;
// allow Ctrl+A
if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
// allow Ctrl+X (cut)
if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
// allow Ctrl+C (copy)
if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
// allow Ctrl+Z (undo)
if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
// allow or deny Ctrl+V (paste), Shift+Ins
if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
|| (e.shiftKey && key == 45)) return true;
// if a number was not pressed
if(key < 48 || key > 57)
{
/* '-' only allowed at start */
if(key == 45 && this.value.length == 0) return true;
/* only one decimal separator allowed */
if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
{
allow = false;
}
// check for other keys that have special purposes
if(
key != 8 /* backspace */ &&
key != 9 /* tab */ &&
key != 13 /* enter */ &&
key != 35 /* end */ &&
key != 36 /* home */ &&
key != 37 /* left */ &&
key != 39 /* right */ &&
key != 46 /* del */
)
{
allow = false;
}
else
{
// for detecting special keys (listed above)
// IE does not support 'charCode' and ignores them in keypress anyway
if(typeof e.charCode != "undefined")
{
// special keys have 'keyCode' and 'which' the same (e.g. backspace)
if(e.keyCode == e.which && e.which != 0)
{
allow = true;
}
// or keyCode != 0 and 'charCode'/'which' = 0
else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
{
allow = true;
}
}
}
// if key pressed is the decimal and it is not already in the field
if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1)
{
allow = true;
}
}
else
{
allow = true;
}
return allow;
}
)
.blur(
function()
{
var val = jQuery(this).val();
if(val != "")
{
var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
if(!re.exec(val))
{
callback.apply(this);
}
}
}
);
return this;
}