/**
 * General classe voor veel voorkomende applicatie handelingen
 */
var $ = jQuery.noConflict();

$.fn.qtip.styles.errorTooltip = {
    tip: {
        corner: 'bottomMiddle',
        color: '#d8362a'
    },
    background: '#d8362a',
    color: '#fff',
    border: { width: 0 },
    fontSize: '13px'
};

Algemeen = function() {
	return {
		
		/**
		 * Vul aautomatich input velden doormiddel van een key val array
		 */
		setInputValByName : function(prefix, data) {
			for(var key in data ){
				if($('input[name=' + prefix + key + ']').length > 0){
					$('input[name=' + prefix + key + ']').val(data[key]);
				}
			}
		},
		
		/**
		* initializatie van de tooltip
		*/
		reloadQtip : function(){
			$(".qtip").qtip({
		        content: { text: false },
		        style: {
		            name: "dark",
		            border: {
		                width: 1,
		                radius: 4
		            }
		        },
		        position: {
		          corner: {
		            target: 'rightMiddle',
		            tooltip: 'leftBottom'
		          }
		        }
		    });						
			$(".qtipError").qtip({
		        content: { text: false },
		        style: {
		            name: "red",
		            border: {
		                width: 1,
		                radius: 2
		            }
		        },
		        position: {
		          corner: {
		            target: 'rightMiddle',
		            tooltip: 'leftBottom'
		          }
		        }
		    });	           			
		}
	};
};
/**
 * Sta alleen nummerice waardes toe
 */
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });
    });
};

(function($) {
  $.fn.ClearTypeFadeTo = function(options) {
      if (options)
              $(this)
                      .show()
                      .each(function() {
                              if (jQuery.browser.msie) {
                                      // Save the original background color
                                      $(this).attr('oBgColor', $(this).css('background-color'));
                                      // Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text)
                                      $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
                              }
                      })
                      .fadeTo(options.speed, options.opacity, function() {
                              if (jQuery.browser.msie) {
                                      // ClearType can only be turned back on if this is a full fade in or
                                      // fade out. Partial opacity will still have the problem because the
                                      // filter style must remain. So, in the latter case, we will leave the
                                      // background color and 'filter' style in place.
                                      if (options.opacity == 0 || options.opacity == 1) {
                                              // Reset the background color if we saved it previously
                                              $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
                                              // Remove the 'filter' style to restore ClearType functionality.
                                              $(this).get(0).style.removeAttribute('filter');
                                              if (options.opacity == 0) {
                                                $(this).hide();
                                              }
                                      }
                              }
                              if (options.callback != undefined) options.callback();
                      });
  };
  
  $.fn.ClearTypeFadeIn = function(options) {
      if (options)
              $(this)
                      .css({ opacity: 0 })
                      .ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
  };
  
  $.fn.ClearTypeFadeOut = function(options) {
      if (options)
              $(this)
                      .css({ opacity: 1 })
                      .ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
  };
  
  $.fn.ClearTypeToggle = function(options) {
      if ($(this).css('opacity') == 1) {
          $(this).ClearTypeFadeOut(options);
      } else {
          $(this).ClearTypeFadeIn(options);
      }
  }
  
  $.fn.vCenter = function() {
      return this.each(function(i){
          var ah = Math.abs( $(this).height() );
          var ph = $(this).parent().height();
          var mh = (ph - ah) / 2;
          $(this).css('margin-top', mh);
      });
  };
})(jQuery);

function showWaitBox() {
	showInfoBox('#footer_default_wait_html', false, 80, 200);	
}

function isNumeric(input){
	   return (input - 0) == input && input.length > 0;
}

function isEmpty( inputStr ) {
	if ( null == inputStr || "" == inputStr || !inputStr.length ) {
		return true; 
	}
	return false; 
}

function isZipcode(strPC) {
	return typeof strPC=='string'
	?strPC.match(/[1-9][0-9]{3} ?[a-zA-Z]{2}/)==strPC
	:false;
}
function isEmail(str) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(str) == false) {
      return false;
   }
   return true;
}




/*function isZipcode(zip) {
	//str=str.replace(/(^\s*)|(\s*$)/g, "");
	  if(!str.match(/^[1-9][0-9]{3}[\s][A-Z]{2}$/i)) {
	    return false;
	  } else {
	    return true;
	  }*/	
	
	
/*	var re = new RegExp("#^[0-9]{4}\s?[a-z]{2}$#i");
	if(zip.match(re)){
		return true;
	}
	return false;*/
	//return zip.match("#^[0-9]{4}\s?[a-z]{2}$#i");
//}

function showInfoBox(pName, pShowClose, pHeight, pWidth, pForceShow) {
	// Naam van de popup div
	var PopupBox = "#footer_popup_box";
	// Bepaal of de popupbox nu zichtbaar is
	var isVisible = ($(PopupBox).css("display") == "none" ? false : true);
	// Toon de popup indien dit wordt afgedwongen (pForceShow) of als deze nu niet zichtbaar is
	if ( (pForceShow === true) || (!isVisible) ) {
		// Content om te tonen bepalen
		var htmlContent = '';
		if ( (pName != undefined) && (pName != '')) {
			htmlContent = $(pName).html();
		}
		if ( (pShowClose != undefined) && (pShowClose == true) ) {
			htmlContent += '<br><a href="javascript:;" onclick="showInfoBox(\'' + PopupBox + '\')" >Sluiten</a>';
		}
		$(PopupBox).html(htmlContent).first();

		// Popup centreren en tonen
		var nHeight = 0;
		var nWidth  = 0;
		if (pHeight != undefined) { nHeight = pHeight; }
		if (pWidth  != undefined) { nWidth  = pWidth; }
		if (nHeight > 0) { $(PopupBox).height(nHeight); }
		if (nWidth > 0) { $(PopupBox).width(nWidth); }
		
		centerPopup(PopupBox, 0, 0);  	
		if (!isVisible) {
			// Popup tonen indien nu nog niet zichtbaar
			$("#footer_background_popup").css({"opacity": "0.7", "z-index": "1"}).next();
			//$("#backgroundPopup").ClearTypeFadeIn({ speed: 600 });
			$("#footer_background_popup").fadeIn("slow").next();
			$(PopupBox).ClearTypeFadeIn({ speed: 600 });
			//$(PopupBox).fadeIn("slow").next();
		}
		waitBoxIsVisible = (!pShowClose) ;
	} else {
		// Popup hiden
		$(PopupBox).ClearTypeFadeOut({ speed: 600});	
		$("#footer_background_popup").fadeOut("slow").next();	

		$(PopupBox).html('').next;
		$(PopupBox).css("display", "none");
		waitBoxIsVisible = false;
	}
			

}
 
function centerPopup(pPopupName, pPopupHeight, pPopupWidth, pInnerDiv){
	var windowWidth = document.body.clientWidth;  
	var windowHeight = window.innerHeight;  
	var popupHeight = pPopupHeight;  
	var popupWidth  = pPopupWidth;  

	if (popupWidth == 0 || popupWidth == null) {
		popupWidth = $(pPopupName).width();
	}
	if (popupHeight == 0 || popupHeight == null) {
		popupHeight = $(pPopupName).height();
	}
	var topX  = ((windowHeight / 2) - (popupHeight / 2));
	var leftX = (windowWidth / 2) - (popupWidth / 2);
   
	$(pPopupName).css({
		"position": "absolute",  
		"top": topX,  
		"left": leftX}).next();  

	if (pInnerDiv != null && pInnerDiv != '') {
		$(pInnerDiv).css({
			"position": "absolute",  
			"top": topX,  
			"left": leftX}).next();  		
	}
  
	
	$("#footer_background_popup").css({ "height": windowHeight}).next();  
   
}  

var showAjaxWaitBox = false; 
var waitBoxIsVisible = false;
var resultModel = new ResultModel(); 
var algemeen = new Algemeen(); 

$(document).ready( function() {
//	$("#main-panel").show();
	

	
/*	

    if ( typeof globalvar_wasjustsaved != "undefined" ) {
        if ( globalvar_wasjustsaved == 1 ) {
            customAlert( "", "Gegevens zijn opgeslagen." );
        }
    }

    $("#footer_popup_box").ajaxStart( function (pHandler) {
    	if (showAjaxWaitBox) { showWaitBox(); }
    }).ajaxComplete( function (pHandler) {
    	if (waitBoxIsVisible) { showWaitBox(); }
    }).ajaxError( function(error, xmlobj, sent) {
        customAlert("Ajax Error",xmlobj.responseText);
    });
    
    $("input.autodatum").change( function() {
        var d = $(this).val();
        if ( d.length == 8 ) {
            var fd = d.substr(0,2) + "/" + d.substr(2,2) + "/" + d.substr(4);
            $(this).val( fd );
        } else {
            
        }
    });					
	
	$( "button, input:submit, input:button" ).button();
	*/
  
  var $loading = $("#loading");
  $("#loading").bind("ajaxSend", function(){
      $loading.ClearTypeFadeIn({speed: '600'});      
  }).bind("ajaxComplete", function(){
      $loading.ClearTypeFadeOut({speed: '600'});
      $loading.hide();
  });  
});

// Posten met de opgegeven action
function SubMitForm(FormNaam, Action)
{    FormNaam = "#" + FormNaam;
	$(FormNaam).attr("action", Action);
	$(FormNaam).submit();
}

function formatArrayDatePicker() {
  return ({
    dateFormat: "dd-mm-yy",
    showAnim: "blind",
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true
  });
}

function formatJqGridDate($p_value, $p_options, $p_rowObject) {
  if ($p_value == 0 || $p_value == '') {
    return '';
  } else {
    // 86400 dag in unix time
    var $n_diff = 0;
    var $n_date = parseInt($p_value, 10) + $n_diff;
    var dDatum = new Date(($n_date  * 1000));    
    
    //return dDatum.toLocaleDateString();
    
    return dDatum.getDate() + '-' + (dDatum.getMonth() + 1) + "-" + dDatum.getFullYear();
  }
    
}

function formatJqGridAfronding(cellvalue, options, rowObject) {
  return Math.round(Math.round(cellvalue * 100) / 100);
}

function browserIE($ps_version) {
  if ($.browser.msie) {
    if ($ps_version == undefined || $ps_version == "") {
      return true;
    }
    if ($.browser.version.slice(0, $ps_version.length) == $ps_version) {
      return true;
    }
  }
  return false;
}

function jqResizeTables($ps_tableid) {
  // Breedte van grid dynamisch resizen om gereserveerde ruimte voor scrollbar te verwijderen.
  var $s_table_id = ($ps_tableid == undefined ? "" : $ps_tableid);

  $("div.ui-jqgrid-view").each(function() {
    
    if (($s_table_id == "") || ($s_table_id != "" && $(this).attr("id") == $s_table_id)) {
      
      var $obj_header_div   = $(this).find("div.ui-jqgrid-hdiv");
      var $obj_header_table = $(this).find("table.ui-jqgrid-htable");
      var $obj_body_div     = $(this).find("div.ui-jqgrid-bdiv");
      var $obj_body_table   = $(this).find("table.ui-jqgrid-btable");
      
      var $n_width = $obj_header_div.width();
      var $n_tableheight = $obj_body_table.height();
      var $n_divheight   = $obj_body_div.height();
      
      if ($n_tableheight > 0 && $n_tableheight > $n_divheight) {
        $n_width = $n_width - 17;
      }
      
      $obj_header_table.css("width", $n_width);
      $obj_body_table.css("width", $n_width);
    }    
  });
  
  if (browserIE()) {
    $('tr.ui-row-ltr').each(function(index){
      $(this).css("background-image", "none");
      $(this).css("filter", "none");
      $(this).css("opacity", "1");
    });
  
    if (browserIE("7")) {
      $('tr.ui-row-ltr td').each(function(index){
        if ($(this).html() == "") {
          $(this).html("&nbsp;");
        }
      });
    }
  }
}

/**
* Controleren of CSS class bestaat
* @param string className
* @return boolean
*/
function cssIsLoaded(className) {
  var test = document.createElement("div");
  test.className = className;
  if (window.getComputedStyle) {
    return getComputedStyle(test, null).display === "none";
  }
  return false;
}

/**
* CSS bestand laden
* @param string filename
*/
function loadCssFile(filename) {
  var head = document.getElementsByTagName("head")[0];
  var element = document.createElement('link');
  element.setAttribute("rel", "stylesheet");
  element.setAttribute("type", "text/css");
  element.setAttribute("href", filename);
  head.appendChild(element);
}

/**
* JavaScript bestand laden
* @param string filename
*/
function loadJsFile(filename) {
  var head = document.getElementsByTagName("head")[0];
  var element = document.createElement('script');
  element.setAttribute("type", "text/javascript");
  element.setAttribute("src", filename);
  head.appendChild(element);
}
