
//timeout for clear messages
var tmm;

// set total reload if we get a Reset Content code (the session 
// has expired and we need to bring user to the login action)


function isEmpty (object)
{
   for(var i in object)
    return false;
  return true;
}



if (typeof('$') != 'undefined') 
{
	$.ajaxSetup({
		complete: function(xhr, statusText)
		{		  
			if (('undefined'!=typeof(xhr)) && isEmpty(xhr) != false && (205 == xhr.status)) 
				document.location.href = '/login';
		}
	});
}


function _$ (id)
{
	return document.getElementById (id);
}

function ajaxUpdate (url, id, callback, loaderid)
{
	updatedZoneId = id;
	
	urlComponents = url.split ('?');
	
	baseUrl = urlComponents[0];
	queryString = urlComponents[1];
	
	if ( typeof (callback) == 'undefined' ) 
		ajaxUpdateCallback = defaultAjaxUpdateCallback;
	else
		ajaxUpdateCallback = callback;
		
	if ( typeof (loaderid) != 'undefined' ) 
	{
		loaderId = loaderid;
		show (loaderId);
	}
	
	if (window.XMLHttpRequest) 
	{
		ajaxSender = new XMLHttpRequest();
	}
	else 
	{
		if (window.ActiveXObject) 
		{
			ajaxSender = new ActiveXObject ("Microsoft.XMLHTTP");
		}
	}
	
	ajaxSender.open("POST", baseUrl, true);
	
	ajaxSender.onreadystatechange = ajaxUpdateCallback;
	
	ajaxSender.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

	ajaxSender.send (queryString);
}

function defaultAjaxUpdateCallback ()
{
	if (ajaxSender.readyState == 4) 
	{
		if (ajaxSender.status == 200) 
		{
			response = ajaxSender.responseText;
						
			updatedZone = _$(updatedZoneId);
			
			if (updatedZone)
				updatedZone.innerHTML = response;
		}
	}
		
	if ( typeof (loaderId) != 'undefined' ) 
		hide (loaderId);
	
}

function ajaxValidate (url, id, formId, loaderId)
{
	valFormId = formId;
		
	ajaxUpdate (url, id, ajaxValidateCallback, loaderId);
}

function ajaxValidateCallback ()
{
	if (ajaxSender.readyState == 4) 
	{
		if (ajaxSender.status == 200) 
		{
			response = ajaxSender.responseText;
			
			if (response == 'OK')
				_$(valFormId).submit();
			else 
			{
				updatedZone = _$(updatedZoneId);
			
			  if ( typeof(updatedZone) != 'undefined')			
				  updatedZone.innerHTML = response;
				  
				if ( typeof (loaderId) != 'undefined' ) 
      		hide (loaderId);
			}
		}
	}

	/*
	if ( typeof (loaderId) != 'undefined' ) 
		hide (loaderId);
  */
}


//submit form via ajax and update resultId
function ajaxFormSubmit (submitId, formId, url, resultId, answersIds, loaderId, idsToShow, idsToHide) {
  
  eForm = document.getElementById(formId);
  
  if (eForm) {   
    
    //deactivate form submit
    senderGlobal = document.getElementById(submitId);
    senderGlobal.disabled = 'disabled';  
    senderGlobal.className = 'side-button-prog';     
    
    //rest is similar as on "ajaxComplexUpdate"
    answersIdsGlobal = answersIds;
	  idsToShowGlobal = idsToShow;	    
    idsToHideGlobal = idsToHide;	    
    
    url = url + '?' + $("#"+formId).serialize();
    	
	  ajaxUpdate (url, resultId, ajaxComplexUpdateCallback, loaderId);    
    	
  }  
  
}


function ajaxComplexUpdate (sender, url, fields, resultId, answersIds, loaderId)
{ 

  //if string, get object
  if (typeof(sender)=='string')
    sender = _$(sender);  
    
  //deactivate button  
  senderGlobal = sender;
  sender.disabled = 'disabled';  
  sender.className = 'side-button-prog';
  
	answersIdsGlobal = answersIds;
	
	url = getValidateUrl (url, fields);	  	
	
  //alert(url);
	
	ajaxUpdate (url, resultId, ajaxComplexUpdateCallback, loaderId);
}


function ajaxComplexUpdateCallback ()
{  
  
	if (ajaxSender.readyState == 4) 
	{
		if (ajaxSender.status == 200) 
		{		  
		  var responseText = fixJsonData(ajaxSender.responseText);		  
		  var result = JSON.parse(responseText);      
			
			// Update answers in page (id's)
			if (result.success=='true') {
  			if (isArray(answersIdsGlobal)) 
  			{
  				for (var i = 0; i < answersIdsGlobal.length; i++)
  				{	  					
  					div_id = answersIdsGlobal[i];  					
  					answerZone = _$(div_id);  					  					
  					
  					//alert(answerZone);
  					
  					if ( answerZone != null && typeof(answerZone) != 'undefined' && 
  					     typeof(result.answers[i]) != 'undefined' && 
  					     result.answers[i] != 'false' )
  					{
  				    //alert('update answerZone');
  						answerZone.innerHTML = result.answers[i];
  			    }  
  				}
  			}
  			else 
  			{
  				answerZone = _$(answersIdsGlobal);
  				  				
  				if ( typeof(answerZone) != 'undefined' && 
  					     typeof(result.answers[0]) != 'undefined' && 
  					     result.answers[0] != 'false' )  
  					answerZone.innerHTML = result.answers[0];
  			}
			}
			
			
			// Put status message as 'the result was...'
			updatedZone = _$(updatedZoneId);						
			if (typeof(updatedZone) != 'undefined' && null != updatedZone) 
			{
				if (result.success=='true')
					updatedZone.className = result.successClass;
				else
					updatedZone.className = result.errorClass;
					
				updatedZone.innerHTML = result.message;
				
				//clean message after 3 seconds				
				if (typeof(tmm)!='undefined')
				  clearTimeout(tmm);
				tmm = setTimeout( function(){updatedZone.innerHTML = ''; }, 3000);
			}			

			
						
			//call "onComplete" function if exists			
			if (result.onComplete) {			
			  //alert(result.onComplete);
        eval(result.onComplete);
			}
			else {			
			  //re-activate button        
        senderGlobal.className = 'button';
        senderGlobal.disabled = '';
			}
			
			// Hide and show some sections after the interaction is done
			if ( (typeof(idsToShowGlobal)!='undefined') && isArray (idsToShowGlobal) )
				for (var i = 0; i < idsToShowGlobal.length; i++) 
					show (idsToShowGlobal[i]);
					
			if ( (typeof(idsToHideGlobal)!='undefined') && isArray (idsToHideGlobal) )
				for (var i = 0; i < idsToHideGlobal.length; i++) 
					hide (idsToHideGlobal[i]);	
		}
	}
}

//show layer
function show (id)
{
	element = _$(id);
	
	if (element)
	{
		element.style.display = '';
	}
}


//hide layer
function hide (id)
{
	element = _$(id);
	
	if (element)
		element.style.display = 'none';
}

function getValidateUrl (baseUrl, fields)
{
	url = baseUrl;	
	var first = true;
	
	for (i=0; i<fields.length; i++)
	{	  
		element = _$(fields[i]);
		
		if (typeof(element) != 'undefined' && element != null)
		{
			if (!(isCheckBoxOrRadioButton(element)) || (element.checked == true))
			{
				if (first == true) 
				{
					url = url + "?";
					first = false;
				}
				else 
				{
					url = url + "&";
				}
							
				//url += fields[i] + "=" + encodeURI(element.value);
				//url += fields[i] + "=" + escape(element.value);
				//url += fields[i] + "=" + element.value;
				url += fields[i] + "=" + encodeURIComponent(element.value);		
				
			}
		}
			
	}
	
	return url;
}

function isCheckBoxOrRadioButton(element)
{   
    if(element == null)
        return false;
		
    return (element.tagName == "INPUT" && ( (element.type.toLowerCase() == "checkbox") || (element.type.toLowerCase() == "radio" ) ) );
} 

//
// Found in http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C720080D723
//
function isArray(obj) 
{
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}



function confirmLinkAction(link) {
  
  //user text
  if (link.id == undefined)  
  {
    text = link;
  }
  else //default text
  {  
    pattern = /[\w\s]+/;
    text = (link.text).match(pattern) + '. Are you sure?';  
  }
  
  if ( confirm(text) )
    return true;
  else
    return false;
  
}


/*** function ajaxFormValidate: validate a form via ajax and execute custom callback ***/


function ajaxFormValidate(formId, updateId, url) 
{
  ///frontend/project/validate/form/project_new_form
  
  valFormId = formId;
 	loaderId = $('#'+formId+' input [type="submit"]');
 	
 	validateUrl = url + '?' + $("#"+formId).serialize(); 	
 	
 	validate2 = getValidateUrl ('/frontend/project/validate/form/project_new_form', new Array ('checkbox_language_id_1', 'checkbox_language_id_2', 'checkbox_language_id_3', 'checkbox_language_id_4', 'checkbox_language_id_5', 'checkbox_language_id_6', 'project_name', 'project_description'));
 	
	ajaxUpdate (validateUrl, updateId, ajaxFormValidateCallback, loaderId);
  
}


//'redefinition' of ajaxValidateCallback, but sending-form-via-ajax after validate-via-ajax
function ajaxFormValidateCallback ()
{
	if (ajaxSender.readyState == 4) 
	{
		if (ajaxSender.status == 200) 
		{
			response = ajaxSender.responseText;
			
			//correct validate
			if (response == 'OK') {
				
			  //now, submit form via ajax
			  submitId = $('#'+valFormId+' input[type="submit"]');
			  action = $('#'+valFormId).attr('action');
			  
			  //alert(action);			  
			  postData = $("#"+valFormId).serialize();			  
			  
			  //send form via ajax
			  $.post(action, postData, function(data){          			    
   				
			    if ( $('#'+updatedZoneId) != 'undefined') 
			    {
			      //updatedZone.innerHTML = data;
				    $('#'+updatedZoneId).fadeOut(function(){
				      $('#'+updatedZoneId).html(data);
				      $('#'+updatedZoneId).fadeIn();
				    });
			    }
          
        });				
		  
			}
			else {
				updatedZone = _$(updatedZoneId);
			
			  if ( typeof(updatedZone) != 'undefined')			
				  updatedZone.innerHTML = response;
			}
		}
	}
		
	if ( typeof (loaderId) != 'undefined' ) 
		hide (loaderId);
}



function fixJsonData(data) 
{
  return data.replace(/(\r\n|\n|\r)/gm, '');
}
