// JavaScript Document

/*function $(element) {
return YAHOO.util.Dom.get(element);
}*/


// JavaScript Document

var uidfu=new Array();

var secondary_validation=true;

$(document).ready(function(){
		process_content();
		addDataTable();
		$(".new_project").click(function(){
			if(current_project_list_div!=''){
				hideDiv(current_project_list_div);	
			}
			ajaxGet("project","new","");								   
		}
	);
	
	$("#close_login").click(function(){
		$("#login_div").slideUp(150);							 
	});
	
	}
);

function is_array(obj) {
	return obj.constructor == Array;
}

function in_array( needle, haystack, strict ) {
    var strict = !!strict;
 
    for(var key in haystack){
        if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ){
            return key;
        }
    }
 
    return false;
}


function isNumber(object,type)
   //  check for valid numeric strings	
   {
   var strString=object.val();
   if(type=='real'){
	   var strValidChars = "0123456789.";
   }else if(type=='int'){
	    var strValidChars = "0123456789";
   }
   var strChar;
   var blnResult = true;
   var periodCheck=false;
   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
   {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
      {
         blnResult = false;
      }
	  if(strChar=='.' && periodCheck==true){
	  	blnResult = false;
	  }
	  
	  if(strChar=='.' && periodCheck!=true){
			periodCheck=true;
		
	  }
      
	  
   }
   if(blnResult==false){
	  	value=object.val();
		
   		object.val(value.substring(0,value.length-1));
   }
}

function addNumberCheck(){
	$('.real_number_only').keyup(function(){
		isNumber($(this),"real");
		
	});
	
	$('.int_number_only').keyup(function(){
		isNumber($(this),"int");
		
	});
	
}




function ajaxGet(type,id,which_div,extra_data){
	url=ajax_get_file+"?type="+type+"&id="+id;
	if(extra_data){
		if(is_array(extra_data)){
			for (i in extra_data){
				url=url+"&"+i+"="+extra_data[i];	
			}
		}
	}
		
	
	$.getJSON(url,function(response){
	
		handleResponse(response);
	});
}

function ajaxPost(){
	$('.ajax_form').attr("action",ajax_post_file);
	$('.ajax_form').submit(function(){tinyMCE.triggerSave(true,true);});
	$('.ajax_form').ajaxForm({'dataType':'json',beforeSubmit:checkValid,'success':function(response) {
		handleResponse(response);		
	}});	
}	

function handleResponse(response){
		whichDiv='';
		no_main_add=false;
		if(response.which_div){
			whichDiv=response.which_div;
		}else if(whichDiv=='' || !whichDiv){
			whichDiv=main_div;
		}	
	
		
		if(response.flash_and_remove==1){
			$("#"+whichDiv).addClass("deleted_row").fadeTo("slow",0,function(){
					$(this).remove();
			});				 	
		}
		
		if(response.update_div){
			for	(x in response.update_div){
				$("#"+x).html(response.update_div[x]);
			}
		}
		
		if(response.add_after==1){
			$("#"+whichDiv).after(response.main);
			no_main_add=1;
		}
		
		if(response.pop_up && response.pop_up!=''){
			
			$("#"+pop_up_content_id).html(response.pop_up);
			//togglePopUpBox('show');
		}
		
		if(response.main && no_main_add==false){
			$("#"+whichDiv).html(response.main);
		}
		
		if(response.project_list){
			$("#"+project_list_div).html(response.project_list);	
		}
		
		process_content();
		loadingScreen("hide");
		whichDiv='';
		
	
}



function ajaxPostFile(which_div){
	$('.ajax_form_file_upload').attr("action",ajax_post_file);
	$('.ajax_form_file_upload').ajaxForm({beforeSubmit:checkValid,'success':function(data) {
	no_main_add=0;
	
	data=data.replace(/\<textarea\>/,"");
	data=data.replace(/\<\/textarea\>/,"");																	
	var response=$.evalJSON(data);		
	response.main=html_entity_decode(response.main);
		if(response.main){
			if(response.which_div){
				whichDiv=response.which_div;
			}else if(which_div==''){
				whichDiv=main_div;
			}else if(response.add_after==1){
				$("#"+whichDiv).after(response.main);
				no_main_add=1;
			}else{
				whichDiv=which_div
			}
			
			if(no_main_add!=1){
				$("#"+whichDiv).html(response.main);
			}
		
			if(response.file_name){
				if($("#"+uidfu[response.file_name])){	
					
					$("#"+uidfu[response.file_name]).remove();	
				}
			}
			
			process_content();
			
		}
		  
      }});	
}


function ajaxPostFile2(which_div){
	$('.ajax_form_file_upload2').attr("action",ajax_post_file);
	$('.ajax_form_file_upload2').ajaxForm({beforeSubmit:checkValid2,'success':function(data) {
	no_main_add=0;
	
	data=data.replace(/\<textarea\>/,"");
	data=data.replace(/\<\/textarea\>/,"");																	
	var response=$.evalJSON(data);		
	response.main=html_entity_decode(response.main);
		if(response.main){
			if(response.which_div){
				whichDiv=response.which_div;
			}else if(which_div==''){
				whichDiv=main_div;
			}else if(response.add_after==1){
				$("#"+whichDiv).after(response.main);
				no_main_add=1;
			}else{
				whichDiv=which_div
			}
			
			if(no_main_add!=1){
				$("#"+whichDiv).html(response.main);
			}
		
			if(response.file_name){
				if($("#"+uidfu[response.file_name])){	
					
					$("#"+uidfu[response.file_name]).remove();	
				}
			}
			
			process_content();
			
		}
		  
      }});	
}	




function addDataTable(){
	//$('.data_table').dataTable({"bAutoWidth":false,"bStateSave": true,"sZeroRecords":"No jobs posted yet","sPaginationType": "full_numbers"});	
	
}


function addDatePicker(){
	//	$('.date_picker').datePicker({startDate:'01/01/1901'}).attr("readonly",true) ;
}



function addPopUpEvents(){
	$('.hidePopUp').click(function(){togglePopUpBox('hide');});
	
	$('.showPopUp').click(function(){togglePopUpBox('show');});
}

function togglePopUpBox(action){
	if(action && action=='show'){
		$("#"+pop_up_continer_id).show();
	}else if(action && action=='hide'){
		$("#"+pop_up_continer_id).hide();	
	}else{
		$("#"+pop_up_continer_id).toggle();	
	}
}


function togglePopUpLoadingBox(action){
	if(action && action=='show'){
		$("#"+pop_up_loading_continer_id).show();
	}else if(action && action=='hide'){
		$("#"+pop_up_loading_continer_id).hide();	
	}else{
		$("#"+pop_up_loading_continer_id).toggle();	
	}
}

function addClockPicker(){
	/*$(".clock_picker").clockpick({
						starthour : 0,
						endhour : 23,
						showminutes : true
						}
).attr("readonly",true) ; 	*/
	
}

function addEffects(){
	addDatePicker();
}

function addEvents(){
	
	
	ajaxPost();
	ajaxPostFile();
	ajaxPostFile2();
	
}

function addDeleteButtonConfirm(){
		$(".delete_button").click(function(){
			if(confirm("Are you sure you want to delete this item?"))
				return true;
			else
				return false;
		});
}

function addValidation(){
	
	$('.ajax_form').unbind("submit");
	$('.ajax_form').formValidation({
		err_class : "invalidInput",
		err_message		: "Please fill all required fields marked in red. Thank you."
			
 		})	
	$('.submit_form').unbind("submit");
	$('.submit_form').formValidation({
		err_class : "invalidInput",
		err_message		: "Please fill all required fields marked in red. Thank you."
			
 		})	
}




function process_content(){
	addValidation();//must be before addEvents
	addEffects();
	addEvents();	
	
	current_project_tab='';
	addNumberCheck();
	addClockPicker();
	
	addDeleteButtonConfirm();
	//addFancyBox();
	
	addLoadingImages();
	
}

function addLoadingImages(){
	$(".loading_small").html('<img src="'+images_dir+'/loadingSmall.gif" />');
}






function checkValid2(){
	d = new Date();
	uidfu[$("#upload_file_value").val()]=d.getTime();
	if(form_validated){
		h='<div id="'+uidfu[$("#upload_file_value").val()]+'">'+$("#upload_file_value").val()+'<span class="loading_small"></span></div>';
		
		$("#upload_file_form").after(h);
		ajaxGet("upload_file_form","new",'','');
	}else{
		return false;	
	}
}

function checkValid(){
	
	if(secondary_validation==true && form_validated==true){
		fvcheck=true	
	}else{
		fvcheck=false;	
	}
	
	return fvcheck;	
}

function showDiv(div_id){
	
	if($("#"+div_id)){
		$("#"+div_id).show();	
	}
		
}

function hideDiv(div_id){
	
	if($("#"+div_id)){
		$("#"+div_id).hide();	
	}
}


function html_entity_decode(str)
{
    try
	{
		var  tarea=document.createElement('textarea');
		tarea.innerHTML = str; return tarea.value;
		tarea.parentNode.removeChild(tarea);
	}
	catch(e)
	{
		//for IE add <div id="htmlconverter" style="display:none;"></div> to the page
		document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
		var content = document.getElementById("innerConverter").value;
		document.getElementById("htmlconverter").innerHTML = "";
		return content;
	}
}


//strings

function getEditableString(id){
	if(id){
		ajaxGet("string",id,'','');		
		
	}
	
}

function getSubNavLink(id,site_id,site_type_id){
	var extra_data=new Array();

	extra_data['site_id']=site_id;
	extra_data['site_type_id']=site_type_id;
	ajaxGet("get_sub_nav_link",id,'',extra_data);		
}	

function addSubNavLink(id,site_id,site_type_id){
	var extra_data=new Array();
	extra_data['parent_nav_link_id']=id;
	extra_data['site_id']=site_id;
	extra_data['site_type_id']=site_type_id;
	
	ajaxGet("sub_nav_link",'new','',extra_data);		
}	


function loadingScreen(toggle){
	if(toggle=='show'){
		$("#"+pop_up_loading_content_id).html("Loading...");
			togglePopUpLoadingBox('show');
	}else if(toggle=='hide'){
		togglePopUpLoadingBox('hide');
	}
}


var old_parent_nav_link='';
function showSubNavs(id){
	var div=$("#"+id);
	
	if(id!=old_parent_nav_link){
		if(div){
			div.slideDown();
		}
		if(old_parent_nav_link!=''){
			$("#"+old_parent_nav_link).slideUp();	
		}
	}
	old_parent_nav_link=id;
	
	
}


function changeCountry(prefix,name){
	var extra_data=new Array();
	var country_id="#"+prefix+"_country";
	if($(country_id).val()!=''){
		extra_data['country_code']=$(country_id).val();
		extra_data['prefix']=prefix;
		extra_data['name']=name;
		var state_tr_id="#"+prefix+"_state_tr";
		if($(state_tr_id)){
			$(state_tr_id).remove();
		}
		ajaxGet("get_states",'get_states','',extra_data);		
	}
}


function editConfig(config_id){



		
		ajaxGet("editConfig",config_id,'','');	
		
	}


function showLogin(){
	$("#login_div").slideDown(150);
		
}






