// JavaScript Document
var tinyMCE='';

var uidfu=new Array();

var secondary_validation=true;

var data_tables_set=0;

var clear_inputs=new Array();

$(document).ready(function(){
		
		process_content();
	
	if($('*').is('#email')){
		checkValidEmail();
	}
	if($('*').is('#email')){
		
		$('#email').css("width","300px");
		$('#email').keyup(function(){
			
			checkValidEmail()
		});
	}
	
	
	$('.clear_value_onclick').focus(function(){
		if(!clear_inputs[$(this).attr("name")]){
			$(this).val("");
			clear_inputs[$(this).attr("name")]=1;
		}
	});
	
	}
	
	
);

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'){
	  object.val(object.val().replace(/[^0-9 \.]+/g,''));	 
	  myVar = object.val().split('.');

		if (myVar.length>2)
		{
			object.val(object.val().slice(0, -1)); 
		}
   }else if(type=='int'){
	    object.val(object.val().replace(/[^0-9]+/g,''));	
		
   }
  
}








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);
	if(tinyMCE){
		$('.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.pop_up && response.pop_up!=''){
			
			$("#"+pop_up_content_id).html(response.pop_up);
			togglePopUpBox('show');
		}
		
		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.main && no_main_add==false){
			
			$("#"+whichDiv).html(response.main);
		}
		
		
		
		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();
			
		}
		  
      }});	
}	




var datatable_checks=new Array();

function addDataTable(){
	
		$('.dttt').each(function(){
			check_name=$(this).attr('id');
			
			if(!check_name){
					do{
						check_name="dtable"+Math.floor(Math.random()*1000000);
					}while(datatable_checks[check_name]);
					
					$(this).attr('id',check_name);	
				}
			
			if(!datatable_checks[check_name]){
				tabl=$(this).dataTable({"bAutoWidth":false,"bStateSave": true,"sZeroRecords":"No records yet.","sPaginationType": "full_numbers"});
				datatable_checks[check_name]=1;
			}
			
										   
	   });	
	
	
}



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(){
	
	
}

function addEffects(){
	addDatePicker();
}

function addEvents(){
	
	
	ajaxPost();
	ajaxPostFile();
	ajaxPostFile2();
	
}

var delete_button_checks=new Array();
function addDeleteButtonConfirm(){
		
			$('.delete_button').each(function(){
				check_name=$(this).attr('id');
				
				if(!check_name){
					do{
						check_name="delbutton"+Math.floor(Math.random()*1000000);
					}while(delete_button_checks[check_name]);
					
					$(this).attr('id',check_name);	
				}
				if(!delete_button_checks[check_name]){
					$(this).click(function(){
						if(confirm("Are you sure you want to delete this item?"))
							return true;
						else
							return false;
					});
					delete_button_checks[check_name]=1;
				}
				
											   
		   });	
		
	
	
		
}

function addValidation(){
	
	$('.ajax_form').unbind("submit");
	$('.ajax_form').formValidation({
		err_class : "invalidInput",
		err_message		: "Please fill all required fields marked in red or any fields that are filled in incorrectly. Thank you."
			
 		})	
	$('.submit_form').unbind("submit");
	$('.submit_form').formValidation({
		err_class : "invalidInput",
		err_message		: "Please fill all required fields marked in red or any fields that are filled in incorrectly. Thank you."
			
 		})	
}




function process_content(){
	
	
	addValidation();//must be before addEvents
	addEffects();
	addEvents();	
	
	current_project_tab='';
	addNumberCheck();
	addClockPicker();
	
	addDeleteButtonConfirm();
	//addFancyBox();
	
	addLoadingImages();
	addDataTable();
}

function addLoadingImages(){
	$(".loading_small").html('<img src="'+images_dir+'/icons/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(form_validated==true){
		return true	
	}else{
		return false;	
	}
	
	
}

function checkSecondaryValid(){
	if(secondary_validation==true){
		return true	
	}else{
		return false;	
	}
	
	
}

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 loadingScreen(toggle){
	if(toggle=='show'){
		$("#"+pop_up_loading_content_id).html("Loading...");
			togglePopUpLoadingBox('show');
	}else if(toggle=='hide'){
		togglePopUpLoadingBox('hide');
	}
}




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+"_"+name+"_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 initTinyMCE(){
	
	tinyMCE.init({   		
		mode : "textareas",
		editor_deselector : "mceNoEditor",
		content_css : "/skin/css/standard.css",
		width : '440',
		height : '550',	
		entity_encoding : "raw", 
		button_tile_map : true, //performance update	
		theme : "advanced",
		skin : "o2k7",
		skin_variant : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",	      
		accessibility_warnings : false,      			
		fix_list_elements : true,
		verify_html : true,
		verify_css_classes : false,
		plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,advimage,advlink,simplepaste",
		theme_advanced_buttons1 : "cut,paste,copy,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,styleselect,formatselect,pasteword,forecolor,backcolor,separator",
		theme_advanced_buttons2 :"bold,italic,underline,strikethrough,advhr,separator,bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,customdropdown,cmslinker,link,unlink,anchor,image,charmap,cleanup,code",  
		theme_advanced_buttons3 : "",
		theme_advanced_blockformats : "p,div,h1,h2,h3,h4,h5,h6,div,blockquote,dt,dd,code,samp",
		document_base_url : "http://www.clearmycarbon.com/",
		relative_urls : true,
		remove_script_host : false,  	
		language: "en",
		dialog_type: "modal",
		apply_source_formatting : true,
		theme_advanced_statusbar_location : 'bottom',
		theme_advanced_path : true,			
		force_br_newlines : false,
		force_p_newlines : true,			 
		forced_root_block : false,		
		plugin_insertdate_dateFormat : "%Y-%m-%d",
		plugin_insertdate_timeFormat : "%H:%M:%S"
	});
	
}

