/* Neo Libary */

neo={};
neo.loadOnComplete = function(moduleName, url, func) {
	new Ajax.Updater(moduleName,url,{method: 'post',evalScripts:true, onComplete: function(transport){func();} });
}
neo.loadModule=function(moduleName, url){ new Ajax.Updater(moduleName,url,{method: 'post',evalScripts:true, onCreate: function(transport){} ,onComplete: function(transport){} });};
neo.update=function(divToUpdate, url){ neo.loadModule(divToUpdate, url);};
neo.request=function(url){new Ajax.Request(url,{method: 'post',evalScripts:true, onCreate: function(transport){showLoading();} ,onComplete: function(transport){hideLoading();} })};

neo.requestWithAdditionalParameters=function(url,extraJSON) {
	
	if (extraJSON == null)
	{
		extraJSON = $H({});	
	}
	new Ajax.Request(url,
	{
		parameters: extraJSON,
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){},
		onComplete: function(transport){} 
	}
	);
	return false;
}

neo.updateWithAdditionalParameters=function(divToUpdate,url,extraJSON) {
	
	if (extraJSON == null)
	{
		extraJSON = $H({});	
	}
	new Ajax.Updater(divToUpdate,url,
	{
		parameters: extraJSON,
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){},
		onComplete: function(transport){} 
	}
	);
	return false;
}


/* Neo - Drag And Drop LIB*/
neo.DragAndDrop={};
neo.DragAndDrop.initDragAndDrop=function(numberOfCols, modulesCol, debug){containmentArea = new Array(numberOfCols);for (var j = 0; j < numberOfCols; j++){	containmentArea[j] = modulesCol + j;}for (var j = 0; j < numberOfCols; j++)	{	var colName = modulesCol + j; Sortable.create(colName,{	hoverclass:'sortableListHover',	dropOnEmpty:true, handle:'handle', containment: containmentArea, constraint:false, onChange:function() {$(debug).innerHTML = Sortable.serialize(colName);}});}}

/* Neo - Cookie LIB*/
neo.Cookie = {}
neo.Cookie.createCookie=function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
}

neo.Cookie.readCookie=function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

neo.Cookie.eraseCookie=function(name) {
	neo.Cookie.createCookie(name,"",-1);
}

/* Neo - Navigation Lib */
neo.Navigation={};
neo.Navigation.setLocation=function(tab,page)
{
	if (tab != null && tab != "")
	{
		if (page != null && page != "")
		{
			var location = "{tab: '"+ tab +"', page: '"+ page +"'}";
			neo.Cookie.createCookie("neo_currentLocation",location,0.5);	
		}
		else
		{
			var location = "{tab: '"+ tab +"'}";
			neo.Cookie.createCookie("neo_currentLocation",location,0.5);
		}
	}
}

neo.Navigation.getLocation=function()
{
	return neo.Cookie.readCookie("neo_currentLocation");
}


/* Neo - Sub Section Lib*/
neo.SubSectionTabs={};
neo.SubSectionTabs.load=function(commonModuleName,subSectionData){
	showLoading();
	if (neo.Cookie.readCookie("neo_currentSubSectionTab") != null)
	{
		var tab = neo.Cookie.readCookie("neo_currentSubSectionTab");
		neo.SubSectionTabs.changeTo(commonModuleName,tab,subSectionData);
	}
	hideLoading();	
}

neo.SubSectionTabs.changeTo=function(commonModuleName,selectedTabId,subSectionData) {
	showLoading();
	neo.Cookie.createCookie("neo_currentSubSectionTab",selectedTabId,0);
	
	if (selectedTabId == 'All')
	{
		
		var arrayClass = $$('li.subModuleActive');
		for (var i =0; i < arrayClass.length; i++ )
		{
			arrayClass[i].removeClassName('subModuleActive');
		}
		$('tabAll').addClassName('subModuleActive');
		
		var array = $$('li.subModule');
		for (var i =0; i < array.length; i++ )
		{
			array[i].style.display = "block";
		}
	}
	else
	{
		var arrayClass = $$('li.subModuleActive');
		for (var i =0; i < arrayClass.length; i++ )
		{
			arrayClass[i].removeClassName('subModuleActive');
		}
		$('tab'+selectedTabId).addClassName('subModuleActive');
		
		var array = $$('li.subModule');
		for (var i =0; i < array.length; i++ )
		{
			array[i].style.display = "none";
		}
		
		var arrayModules = subSectionData.get(selectedTabId);
		for (var i =0; i < arrayModules.length; i++ )
		{
			$(commonModuleName+arrayModules[i]).style.display = "block";
		}
		
	}
	hideLoading();
	return false;
}


neo.changeToTab=function(selectedTab,tabId){
		 var tabsToDisable = selectedTab.parentNode.parentNode.childNodes;
		 for (var i=0; i< tabsToDisable.length; i++)
		 {
		 if (tabsToDisable[i].nodeType == 1)
		 {
		 tabsToDisable[i].className = null;
		
		 // As safari doesnt support the tabIndex attribute if using safari get it a diffrent way
		 if (BrowserDetect.browser == "Safari")
		 {
		 var tabsToDisableContent = document.getElementById(tabId + tabsToDisable[i].getAttribute("tabindex"));
		 tabsToDisableContent.className = "tabInactive";
		 }
		 // All other Browsers
		 else
		 {
		 var tabsToDisableContent = document.getElementById(tabId + tabsToDisable[i].tabIndex);
		 tabsToDisableContent.className = "tabInactive";
		 }
		 }
		 }
		 selectedTab.parentNode.className = "currentSearch";
		
		 // As safari doesnt support the tabIndex attribute if using safari get it a diffrent way
		 if (BrowserDetect.browser == "Safari")
		 {
		
		 var selectedTabContent = document.getElementById(tabId + selectedTab.parentNode.getAttribute("tabindex"));
		selectedTabContent.className = "tabActive";
		 }
		 // All other Browsers
		 else
		  {
		 var selectedTabContent = document.getElementById(tabId + selectedTab.parentNode.tabIndex);
		 selectedTabContent.className = "tabActive";
		 }
		
		 return false;
}

/* Form Lib */
neo.form = {};
neo.form.submit = function(formName) {
	
	new Ajax.Updater("alertBoxContent",$(formName).action,
	{
		parameters: $(formName).serialize(true),
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){showLoading();},
		onComplete: function(transport){showAlert(); hideLoading();} 
	}
	);
	return false;
}

//removed loading
neo.form.submitWithOnComplete = function(cssClass,url,divToUpdate,onComplete) {

	var elements = $$("."+cssClass);
	var extraJSON = $H({});	
	
	for (var index = 0, len = elements.length; index < len; ++index) {
	  var item = elements[index];
	   alert(Object.toJSON(item));
	  extraJSON = extraJSON.merge(item.serialize(true));
	  alert(extraJSON.toJSON());
	}
	
	new Ajax.Updater(divToUpdate,url,
	{
		parameters:extraJSON,
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){},
		onComplete: function(transport){onComplete;} 
	}
	);
	return false;
}

neo.form.submitWithConfirm = function(formName,message) {
	var formUrl = "neo.form.submit('" + formName + "');closeAlertBox();";
	loadConfirmBoxForFunc(formUrl,message);
	return false;
}

neo.form.submitToDivWithConfirm = function(formName,message,divId) {
	alert(formName);
	var formUrl = "neo.form.submitToDiv('" + formName + "', '" + divId + "', null);closeAlertBox();";
	loadConfirmBoxForFunc(formUrl,message);
	return false;
}


neo.form.submitToDiv = function(formName,divToUpdate, extraJSON) {
	if (extraJSON == null)
	{
		extraJSON = $H({});	
	}
	new Ajax.Updater(divToUpdate,$(formName).action,
	{
		parameters: extraJSON.merge($(formName).serialize(true)),
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){},
		onComplete: function(transport){} 
	}
	);
	return false;
}
neo.form.submitToDivWithOnComplete = function(formName,divToUpdate, func) {
	
	
	new Ajax.Updater(divToUpdate,$(formName).action,
	{
		parameters: $(formName).serialize(true),
		method: 'post',
		evalScripts:true, 
		onCreate: function(transport){},
		onComplete: function(transport){func();} 
	}
	);
	return false;
}
neo.form.submitWithAdditionalParams = function(formName, extraJSON)
{
	neo.form.submitToDiv(formName,"alertBoxContent",extraJSON)
}

neo.form.date = function(dateYear, dateMonth, dateDay) { 
	var today=new Date();
	
	//alert(BrowserDetect.browser);
	if(BrowserDetect.browser == "Explorer" || BrowserDetect.browser == "Opera")
	{
		$(dateYear).value = today.getYear();
	}
	else
	{
		$(dateYear).value = today.getYear() + 1900;
	}
	
	$(dateMonth).selectedIndex = today.getMonth()+1;
	$(dateDay).selectedIndex = today.getDate();
	return false;
}
neo.form.datePlusNDays = function(dateYear, dateMonth, dateDay,extraDays) { 
	var today=new Date();
	today.setDate(today.getDate()+extraDays);
	$(dateYear).value = today.getYear() + 1900;
	$(dateMonth).selectedIndex = today.getMonth()+1;
	$(dateDay).selectedIndex = today.getDate();
	return false;
}

neo.form.initSubSelect = function(sourceName, targetName,targetFullName, targetAcronymName) {
	var source = $(sourceName);
	var target = $(targetName);
	var targetAcronym = $(targetAcronymName);
	var targetFull = $(targetFullName);
	
	subSelect = {
		// some stuff our 'generic' function needs
  		change: function(event) {
    		neo.form.changeSubSelect(event.element(),target,targetFull,targetAcronym);
  		}
	};
	
	source.observe('change', subSelect.change.bindAsEventListener(subSelect));

	
	if (source.getValue() != -1)
	{
		neo.form.changeSubSelect(source,target,targetFull,targetAcronym)
		
	}

	for (var i=0; i < target.options.length; i++)
	{
		var option = target.options[i];
		
		if (option.value == targetFull.getValue())
		{
			option.selected = true;	
		}
	} 
} 

neo.form.changeSubSelect =  function(source,target,targetFull,targetAcronym) {
  	
  	

  	superValue = $(source).getValue();
  	
  	var subs =new Array();
  	var x=0;
  	// Make array of ints
	for (var i=0; i < targetAcronym.options.length; i++)
  	{
  		var option = targetAcronym.options[i];
  		
  		var optionArray = option.text.split(",");
  		
  		for (var j=0; j < optionArray.length; j++)
  		{
  			if (optionArray[j] ==  superValue)
  			{
  				
  				subs[x] = option.value;
  				x++;
  			}
  		}
  	}

  	//Remove all Current
  	for (var j = target.length - 1; j>=1; j--)	
  	{	
  		target.remove(j)
  	}
  	
  	for (var k=0; k < targetFull.length; k++)
  	{
  		var option = targetFull.options[k];
  		if ($(subs).indexOf(option.value) != -1)
  		{
  			 var optNew = document.createElement('option');
  			 optNew.text = option.text;
  			 optNew.value = option.value;
             		
  		
 	 		try {
	  		  target.add(optNew, null); // standards compliant; doesn't work in IE
	  		}
	  		catch(ex) {
	  		  target.add(optNew); // IE only
	  		}	
  		}
  	}
  	
  	  
  	
  	
}

neo.form.textAreaLimit = function(field, countfield, maxlimit) {
		if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		
		else 
		countfield.value = maxlimit - field.value.length;
}

neo.form.select = {};

neo.form.select.add = function(selectId, id, value) {

	 var newOption=document.createElement('option');
	 newOption.text = value;
	 newOption.value = id;

	$(selectId).add(newOption,null);
	$(selectId).selectedIndex = $(selectId).options.length -1;
	$(selectId).focus();
	
}

neo.form.texphone = function(checkBoxId)
{	
	var phonenumberBox = document.getElementById("phonenumberBox");
	if (checkBoxId.checked)
	{
		phonenumberBox.value += " (Textphone)"; 
	}
	else
	{
		phonenumberBox.value = "";
	}
}

/* PARSE DATE to target */
neo.parseDate=function(day,month,year,target)
{
	if ($(day) != null && $(month) != null && $(year) != null && $(target) != null)
	{
		if (
			($(day).options[$(day).selectedIndex].value != "-1")
			&&
			($(month).options[$(month).selectedIndex].value != "-1")
			&& 
			($(year).value.length == 4)
			&&
			(parseInt($(year).value) > 1000)
			) 
		{
			$(target).value = parseInt($(year).value) + "-" + $(month).options[$(month).selectedIndex].text + "-" + $(day).options[$(day).selectedIndex].text;	
		}
		else
		{
			$(target).value = "";
		}
	}
}

neo.parseDateDDMMYYYY=function(day,month,year,target)
{
	if ($(day) != null && $(month) != null && $(year) != null && $(target) != null)
	{
		if (
			($(day).options[$(day).selectedIndex].value != "-1")
			&&
			($(month).options[$(month).selectedIndex].value != "-1")
			&& 
			($(year).value.length == 4)
			&&
			(parseInt($(year).value) > 1000)
			) 
		{
			$(target).value = $(day).options[$(day).selectedIndex].value  + "/" + $(month).options[$(month).selectedIndex].value + "/" +parseInt($(year).value);
		}
		else
		{
			$(target).value = "";
		}
	}
}


/* PARSE Select to target */
neo.parseSelect=function(select,target)
{
	if ($(select) != null && $(target) != null)
	{
		var selected  = "";
		for (var i=0; i < $(select).options.length; i++)
		{
			if ($(select).options[i].selected)
			{
				
				if ($(select).options[i].value == "")
				{
					selected="";
					for (var i=0; i < $(select).options.length; i++)
					{
						$(select).options[i].selected = false;
					}
					break;
				}
				selected = selected + $(select).options[i].value+ "-#-";
			}
		}
		$(target).value = selected;
	}
}


neo.form.findSOACodeWard = function(questionId) {
	
	var quesInCal = $("questionsIdsInCal_"+questionId).value;
	
	var qCalAnsArr = findAnswer(quesInCal);
	
	var derivedAnswerDiv = "derivedAnswerDiv_"+questionId;
	var projectId = $("projectId").value;
	
    var url = "publicRegistrationAction-getSOACode.action?questionId="+questionId+"&postCode=" + qCalAnsArr[0] +"&projectId="+projectId;
    
    neo.loadModule(derivedAnswerDiv,url);
	
}

function findAnswer(quesInCal){
	
	if(quesInCal.search("|")!=-1){
		var qCalArr = quesInCal.split("|");
	}else{
		var qCalArr = quesInCal;
	}
	
	var qCalAnsArr = new Array();
	
	for (var i=0; i < qCalArr.length; i++)
	{
		qCalAnsArr[i] = $("questionIds_"+qCalArr[i]).value;
	}
	
	return qCalAnsArr;
}







/* CSS Lib */
neo.css = {};
neo.css.addCss=function(cssCode){
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);

}

function loadEditCvSection(mcSecId){
	window.parent.location.href = "assistedCvBuilderAction-editCvAnswer.action?save=true&mcSectionId="+mcSecId;
}

function loadCvSection(cvSecId, cvSecEleId){
	window.parent.location.href = "assistedCvBuilderAction-findNextSectionOrQues.action?sectionId="+cvSecId+"&sectionElementId="+cvSecEleId;
}

function loadPersonalDetailsSection(){
	window.parent.location.href = "assistedCvBuilderAction-editPersonalDetails.action?editPersonal=true";
}

function startAgainConfirm(cvSecId, cvSecEleId){
	if(confirm("If you click OK all the existing data of this section will be deleted. Do you want to continue?")){
		window.location.href = "assistedCvBuilderAction-findNextSectionOrQues.action?startAgain=true&sectionId="+cvSecId+"&sectionElementId="+cvSecEleId;
	}
}

function createNewCvConfirm(){
	if(confirm("If you click OK all the existing data of this CV will be deleted. Do you want to continue?")){
		window.location.href = "assistedCvBuilderAction-deleteCvDetails.action";
	}
}

function loadCv(){
	document.getElementById("loadCv").src = "showCvAction.action";	
	$('loadingCvBoxIframe').style.display = "block";
	$('maskCv').style.display = "block";
	$('alertCvBoxWithIFrame').style.display = "block";
}

function closeCvBox(){
	$('loadingCvBoxIframe').style.display = "none";
	$('maskCv').style.display = "none";
	$('alertCvBoxWithIFrame').style.display = "none";	
}

function loadSectionList(){
	$('sectionList').style.display = "block";
}

function closeSectionList(){
	$('sectionList').style.display =  "none";
}

function postCodeBoundaryCheck() {
	var postCode = $('postcodeId').value;
	neo.update('postcode_boundary_message','publicRegistrationAction-checkBoundaryPostCode.action?postCode='+postCode);
}
