// ---------------------------------------------------------------------
// Open new browser window
//
// Params:
//
//   pWidth - popup width in px
//   pHeight - popup height in px
//   pXpos - x window position or one of: center, left, right
//   pYpos - y window position or one of: center, top, bottom
//   pURL - URL to open in window - optional
//   pWindowName - name of window - optional
//   pFocusAfterLoad - focus window after load
//   pAddon - turn on addons. give what addons you want to enable separated by ,
//            ie: scrollbars,hotkeys,location,menubar,resizable,titlebar,toolbar
//   pUseOpener - will add property to the window called opener which would have the this window reference
// ---------------------------------------------------------------------
function PopupWindow(pWidth, pHeight, pXpos, pYpos, pURL, pWindowName, pFocusAfterLoad, pAddon, pUseOpener) {

  // Position X
  if ('center' == pXpos) {
    pXpos = Math.round((screen.width -  pWidth) / 2);
  }
  else if('left' == pXpos) {
    pXpos = 0;
  }
  else if('right' == pXpos) {
    pXpos = screen.width -  pWidth;
  }

  // Position Y
  if ('center' == pYpos) {
    pYpos = Math.round((screen.height - pHeight) / 2);
  }
  else if('top' == pYpos) {
    pYpos = 0;
  }
  else if('bottom' == pYpos) {
    pYpos = screen.height - pHeight;
  }

  var addons = '' +
    'hotkeys=no' +
    ',location=no' +
    ',menubar=no' +
    ',resizable=no' +
    ',scrollbars=no' +
    ',status=no' +
    ',titlebar=no' +
    ',toolbar=no';

  // Replace addons to yes - ie. status=no -> status=yes
  if (pAddon) {
    splitaddons = pAddon.split(',');

    for(i = 0; i < splitaddons.length; i++) {
      regexp = new RegExp(splitaddons[i] + '=no', 'i');
      addons = addons.replace(regexp, splitaddons[i] + '=yes');
    }
  }

  windowhandle = window.open(
    pURL, pWindowName,
    'height=' + pHeight +
    ',width=' + pWidth +
    ',screenX=' + pXpos +
    ',screenY=' + pYpos +
    ',left=' + pXpos +
    ',top=' + pYpos +
    addons
  );

  // Raise window after window load
  if (true == pFocusAfterLoad) {
    windowhandle.focus();
  }

  if(true == pUseOpener){
    windowhandle.opener = window;
  }

  return windowhandle;
}

  //////////////////////////////////////////////
 // This part is for window.onload operations//
//////////////////////////////////////////////

window.onload = function() {
  //Reduce the font size on buttons etc. if they don't fit in, works on given classes.
  //If you want to activate it on your tag, then add the class 'font_adjust' to it.

  //FontAdjustAll(new Array('font_adjust','button_big', 'button_small', 'new_button_standard'));
  //FitLongestWordAll();
};

//gets all elements of certain class/classes
function getElementsByClass(searchClass) {
	var classElements = new Array();
	var els = document.getElementsByTagName('*');
	var elsLen = els.length;
	var pattern = new RegExp("\\b"+searchClass+"\\b");
	for (i = 0; i < elsLen; i++) {
		if (pattern.test(els[i].className)) {
			classElements.push(els[i]);
		}
	}
	return classElements;
}


function FontAdjustAll(theClass) {
  if(!(theClass instanceof Array)){
	  var firstSearch = theClass;
	  theClass = new Array();
	  theClass[0] = firstSearch;
	}
	for (k = 0; k < theClass.length; k++){
    var adjustedClass = getElementsByClass(theClass[k]);
    for(var i = 0; i < adjustedClass.length; i++){
      FontAdjust(adjustedClass[i]);
    }
	}
}

function FontAdjust(pEl){
  if(document.defaultView){
    var MaxHeight = (document.defaultView.getComputedStyle(pEl, '').getPropertyValue('height').replace('px', '') *0.80);
    if(navigator.appName == 'Opera'){
      MaxHeight = MaxHeight * 0.8;
    }
  }else if(pEl.currentStyle){
    var MaxHeight = (pEl.currentStyle.height.replace('px', '') * 0.80);
  }

  //dodane, bo w Operze przy niewidocznych buttonach (np. Update vat id) wychodzilo = 0 i sie zapetlala dalsza czesc
  if(0 != MaxHeight){
	  var d = document.createElement('div');
	  document.body.appendChild(d);
	  if(document.defaultView){
	    d.style.fontSize = document.defaultView.getComputedStyle(pEl, '').getPropertyValue('font-size');
	    d.style.fontWeight = document.defaultView.getComputedStyle(pEl, '').getPropertyValue('font-weight');
	    d.style.width = document.defaultView.getComputedStyle(pEl, '').getPropertyValue('width').replace("px", "") -2 + "px";
	  }else if(pEl.currentStyle){
	    d.style.fontSize = pEl.currentStyle.fontSize;
	    d.style.fontWeight = pEl.currentStyle.fontWeight;
	    d.style.width = pEl.currentStyle.width.replace("px", "") - 2 +'px';
	  }
	  if(pEl.innerHTML){
	    d.innerHTML = pEl.innerHTML;
	  }else if(pEl.type == 'button' || pEl.type == 'submit'){
	    d.innerHTML = pEl.value;
	  }
	  while(d.clientHeight > MaxHeight){
	    d.style.fontSize = (d.style.fontSize.replace("px", "") -1)+'px';
	  }

	  pEl.style.fontSize = d.style.fontSize;
	  document.body.removeChild(d);
	}

  //jeszcze szerokosc...
  var childEl = pEl.childNodes[0];

  if(undefined != childEl && '#text' != childEl.nodeName && undefined != childEl.nodeName){
  	while(childEl.offsetWidth + 10 > pEl.style.width.replace("px", "") && childEl.style.fontSize.replace("px", "") > 5){
  		childEl.style.fontSize = childEl.style.fontSize.replace("px", "") -1 + 'px';
  	}
  }
  else {
		if(pEl.type == 'button' || pEl.type == 'submit'){
			var content = pEl.value;
		}
		else{
			var content = pEl.innerHTML;
		}
		var f = document.createElement('span');
		f.style.fontSize = pEl.style.fontSize;
		f.style.fontWeight = pEl.style.fontWeight;
  	document.body.appendChild(f);
  	f.innerHTML = content;

  	while(f.offsetWidth > pEl.offsetWidth && f.style.fontSize.replace("px", "") > 6 && pEl.offsetWidth > 0){
  		f.style.fontSize = f.style.fontSize.replace("px", "") -1 +"px";
  	}
  	pEl.style.fontSize = f.style.fontSize;

  	document.body.removeChild(f);
  }
}

/**
 * Reduces font size of all elements with class 'FitLongestWord'
 * until the longest word fits the wanted width of the elements
 **/
function FitLongestWordAll(){
  var adjustedClass = getElementsByClass('FitLongestWord');
  for(var i = 0; i < adjustedClass.length; i++){
  	FitLongestWord(adjustedClass[i]);
  }
}

function FitLongestWord(pEl){
	var words = pEl.innerHTML.split(' ');
	var longestWord = '';
	for(var i = 0; i < words.length; i++){
		if(words[i].length > longestWord.length){
			longestWord = words[i];
		}
	}

	var g = document.createElement('span');
	g.style.fontSize = pEl.style.fontSize;
	if(document.defaultView){
		g.style.fontSize = document.defaultView.getComputedStyle(pEl, '').fontSize.replace("px", "") + 'px';
		g.style.fontWeight = document.defaultView.getComputedStyle(pEl, '').fontWeight;
	}
	else if(pEl.currentStyle){
		g.style.fontSize = pEl.currentStyle.fontSize;
		g.style.fontWeight = pEl.currentStyle.fontWeight;
	}
	document.body.appendChild(g);
	g.innerHTML = longestWord;

	while(g.offsetWidth > pEl.offsetWidth && g.style.fontSize.replace("px", "") > 6){
		g.style.fontSize = g.style.fontSize.replace("px", "") -1 +"px";
	}
	pEl.style.fontSize = g.style.fontSize;

	document.body.removeChild(g);
}

function addEvent(pObj, pType, pFunc){
  if(pObj.attachEvent) {
    pObj['e'+pType+pFunc] = pFunc;
    pObj[pType+pFunc] = function(){pObj['e'+pType+pFunc]( window.event );}
    pObj.attachEvent('on' + pType, pObj[pType+pFunc]);
  }
  else{
    pObj.addEventListener(pType, pFunc, false);
  }
}

function removeEvent(pObj, pType, pFunc){
  if(pObj.detachEvent) {
    pObj.detachEvent('on' + pType, pObj[pType + pFunc]);
    pObj[pType + pFunc] = null;
  }
  else{
    pObj.removeEventListener(pType, pFunc, false);
  }
}

function LoadScript(pScriptName){
	var head= document.getElementsByTagName('head')[0];
   	var script= document.createElement('script');
   	script.type= 'text/javascript';
   	script.src= pScriptName;
   	head.appendChild(script);
}

function setCookie(pName, pValue)
{
	var exdate=new Date();
	var expiredays = 1;
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = pName + "=" + escape(pValue) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function showLoadIndicator(pButtonId)
{
	button = $('#'+pButtonId).get(0);
	if(button)
	{	
		button.style.display = 'none';
		$('#'+pButtonId+'_loadindicator')[0].style.display = 'block';	
	}
}
function hideLoadIndicator(pButtonId)
{
	button = $('#'+pButtonId).get(0);
	if(button)
	{
		button.style.display = 'block';
		$('#'+pButtonId+'_loadindicator')[0].style.display = 'none';	
	}
}

function isNumberKey(e)
{
	var unicode = e.charCode? e.charCode : e.keyCode
	if (unicode!=8)  //if the key isn't the backspace key (which we should allow)
	{
		if (unicode<48||unicode>57) //if not a number
			return false //disable key press
	}
}

function isNumberKeySpace(e)
{
	var unicode = e.charCode? e.charCode : e.keyCode
    		if (unicode!=8 && unicode!=32) //if the key isn't the backspace key (which we should allow)
    		{
      		if (unicode<48||unicode>57) //if not a number
        			return false //disable key press
  	}
}

jQuery.fn.slideFadeToggle = function(speed, easing, callback)
{
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};

function goBack(pToStep)
{
	$('form').find('input[type=hidden][name=action]').val(pToStep);

	if('step1' == pToStep)
		$('form').find('input[type=hidden][name=referrer]').val('');

	$('form').submit();
}

function submit_guestbook()
{
	var form = $('#questbook_form');

	toggle_indicatior('on');
		
	$.ajax({
		type: 'POST', 
		url: '/ajax/guestbook.html?action=add', 
		dataType: 'json', 
		data:{
			firstname:form.children('[[name=firstname]').val(),
			lastname:form.children('[name=lastname]').val(),
			email:form.children('[name=email]').val(),
			phone:form.children('[name=phone]').val(),
			goal:form.children('[name=goal]').val()			 
		},
		success : function(ret){					
			
      		if(1 == ret.status) // jest okej 
				$('.panel')[0].innerHTML = ret.msq;
			else
			{
				toggle_field_error('firstname', 'off', '');
				toggle_field_error('lastname', 'off', '');
				toggle_field_error('phone', 'off', '');
				toggle_field_error('email', 'off', '');
												
				toggle_indicatior('off');
				
				for(i =0; i < ret.errors.length; i++)
				{										
					toggle_field_error(ret.errors[i].field, 'on', ret.errors[i].msg);	 				
				}
													
			}	
		},
		error : function(ret)
      	{
      		toggle_indicatior('off');
      	}
		
	});
	
}

function toggle_indicatior(pPosition)
{
	if('on' == pPosition)
	{
		$('#form_layer')[0].style.display = 'none';
		$('#indicator_layer')[0].style.display = 'block';	
	}
	else
	{
		$('#indicator_layer')[0].style.display = 'none';
		$('#form_layer')[0].style.display = 'block';				
	}
}

function toggle_field_error(pField, pPosition, pMessage)
{
	if('on' == pPosition)
	{
		$('#error_'+pField)[0].style.display = 'block';
		$('#error_'+pField)[0].innerHTML = pMessage;
		$('[name='+pField+']')[0].className = 'input_error';	
	}
	else
	{
		$('#error_'+pField)[0].style.display = 'none';
		$('#error_'+pField)[0].innerHTML = '';
		$('[name='+pField+']')[0].className = '';			
	}
}
	