function ratings_submit_survey( form ){
    new Ajax.Updater('search_results', '/?mode=ajax&call=ratings', {
        data: Form.serialize( form )
        ,success: function(){
            alert('Your rating for this project has been submitted.');
            location.reload(true);
        }
    });
}
function highlightme(id)
{
	var img = document.getElementById(id);
	var imgcontrols = document.getElementById('img_'+id);
	img.css('background','silver');
	imgcontrols.css('visibility','visible');
}
function unhighlightme(id)
{
	var img = document.getElementById(id);
	var imgcontrols = document.getElementById('img_'+id);
	img.css('background','white');
	imgcontrols.css('visibility','hidden');
}

function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
} 
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.val();
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].val();
		}
	}
	return "";
}
function selectAll(selectElement)
{
  List = selectElement;
  var temp2 = "";
  var seperator = ","
  
  if (List.length == 0)
  	return false;
  
  for (i=0;i<List.length;i++)
  {
     temp2 = temp2 + List.options[i].value + seperator;
  }
  return temp2;
 
}
function loadForm(saveForm,ignore)
{
	var content = '{ ';
	oTextBoxes = new Array();
	returnThis = new Array();
	
	var elem = document.getElementById(saveForm).elements;
	for(var i=0; i < elem.length; i++)
	{
		var ignoreThis = false;
		
		for (var i2=0;i2 <= ignore.length; i2++)
		{
			if (ignore[i2]==elem[i].id)
				{ignoreThis = true; break;}
		}
		
		if (ignoreThis == true)
			continue;
		//alert(elem[i].type);
		if ( elem[i].type == 'text' || elem[i].type == 'textarea' || elem[i].type == 'password' || elem[i].type== 'select-one' || elem[i].type == "hidden" ) {
			oTextBoxes.push( elem[i] ); // found one - store it in the oTextBoxes	array
			elem[i].value = elem[i].value.replace(/(')/g, "''");
			//'
			if (i == elem.length -1)
				content += "\"" + elem[i].id + "\":\"" + elem[i].value +"\"";
			else
				content += "\"" + elem[i].id + "\":\"" + elem[i].value +"\",";
		}
		else if (elem[i].type == "checkbox")
		{
			if (elem[i].checked == false)
				continue;
			else
			{
				oTextBoxes.push( elem[i] ); // found one - store it in the oTextBoxes	array
				elem[i].value = elem[i].value.replace(/(')/g, "''");
				//'
				if (i == elem.length -1)
					content += "\"" + elem[i].id + "\":\"" + elem[i].value +"\"";
				else
					content += "\"" + elem[i].id + "\":\"" + elem[i].value +"\",";
			}
		}
		else if (elem[i].type == 'select-multiple')
		{
			var multiSelect = selectAll(elem[i]);
			if (i == elem.length -1)
				content += "\"" + elem[i].id + "\":\"" + multiSelect +"\"";
			else
				content += "\"" + elem[i].id + "\":\"" + multiSelect +"\",";
			
		}
		else if(elem[i].type == 'radio')
		{
			var checkedVal = getCheckedValue(elem[i]);
			if (i == elem.length -1)
			{
				if (checkedVal !="")
					content += "\"" + elem[i].id + "\":\"" + checkedVal +"\"";
			}
			else
			{
				if (checkedVal !="")
					content += "\"" + elem[i].id + "\":\"" + checkedVal +"\",";
			}
		}
		//else
			//alert(elem[i].type);	
	}
	
	content +=' }';
	returnThis['elements']=oTextBoxes;
	returnThis['json']=content;
	
	return(returnThis);

}
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function saveForm(formName,ignore,params)
{
	var savebutton = $('#'+formName+'_button');
	var savevalue = savebutton.val();
	savebutton.val('Saving... Please Wait');
	savebutton.attr("disabled", true);
     
    // SELECT ALL OPTIONS
	if (formName == 'companytype'){
        $("#selectedc option").attr("selected","selected");
    }
    if (formName == "serviceareasForm"){
        $("#serviceselected option").attr("selected","selected");
    }
    
    var saveMe = JSON.stringify($('#'+formName).serializeObject());
    
    
    var saveForm = $.ajax({ 
                        url: '/index.php?mode=ajax&call=saveform&form='+formName+'&'+params,
                        type: 'POST',
                        data: {json:saveMe},
                        dataType: "json",
	//new Ajax.Request('/index.php?mode=ajax&call=saveform&form='+formName+'&'+params,
  //{
    //type:'post',
    //data:{savejson: saveMe['json']},
    success: function(data){
      if (data.good.length!=0){
					for ( var i=0, len=data.good.length; i<len; ++i ){
					 $('#'+data.good[i]).css('background', "white");
				}
    	}
      if (data.errors==1)
    	{
    		
    	savebutton.attr('disabled',true);
    	
      	for ( var i2=0, len2=data.fixme.length; i2<len2; ++i2 ){
				 	$('#'+data.fixme[i2]).css('background',"yellow");
				}
			}
	
	  if (formName=="projecttype" || formName=="projectareas" || formName=="serviceareasForm" || formName=="companytype")
	  {
	  	
	  }
	  else
	  	alert(data.msg);
	  	
	  savebutton.attr('disabled', false);
	  
	  if (formName=="refer")
	  {
	  	$('#email1').val('');
	  	$('#email2').val('');
	  	$('#email3').val('');
	  	$('#email4').val('');
	  	$('#email5').val('');
	  	
	  }
      
	  savebutton.attr('disabled', false);
      savebutton.val( savevalue);
      if (formName=="changepassword")
      {
      	$('#oldpassword').val('');
      	$('#password1').val('');
      	$('#password2').val('');
      }
      if(formName=="forgotpassword")
      {
      	$('#email').val('');
      }
      if (data.errors==0 && formName=='newpassword')
      {
      	document.location='index.php';
      }
      if (data.errors==0 && formName=='messageinbox')
      {
      	document.location='index.php?m=myinbox';
      }
      if (data.errors==0 && formName=='messagearchived')
      {
      	document.location='index.php?m=myinbox';
      }
      if (formName=="projecttype")
      {
      	update_planning_project_checklist($('project_id').value);
      }
      if (formName=="projectareas")
      {
      	update_planning_project_checklist($('project_id').value);
      }
      if (formName=="saveproject")
      {
      	update_planning_project_checklist($('project_id').value);
      }
      if (formName=='profile')
			{
				if (data.emailchanged == true)
				{
					$.ajax({ 
                        url:'index.php?mode=ajax&call=logout',
  					
  						success: function(response){
      					
      					document.location='./';
  						}
  					}  					
					)
				}
				if (data.errors==0)
				{
					document.location='/index.php?m=changeprofile&show=update&mode=rebuild';
				}
			}
			
	if (formName=='userprofile')
			{
				if (data.emailchanged == true)
				{
					$.ajax({ 
                        url:'index.php?mode=ajax&call=logout',
  					
  						success: function(response){
      					
      					document.location='./';
  						}
  					}  					
					)
				}
				if (data.errors==0)
					document.location='/index.php?m=userprofile&mode=rebuild';
			}
    }
    
  });
}

function validate_refer(){
	var email = $('#from_email').val();
	var name = $('#from_email').val();
	var failed = false;
	var email1 = $('#email1');
	var email2 = $('#email2');
	var email3 = $('#email3');
	var email4 = $('#email4');
	var email5 = $('#email5');
	var msg = "The following problems occurred \n";
	var emails = Array('email1','email2','email3','email4','email5');
	
	if (name == "")
	{
		msg = msg + "Your Name: is empty \n"
		failed = true;
	}
	
	if (check_email(email) == false)
	{
		//alert(email);
		failed = true;
		msg = msg + "Your Email: is not correct! \n";
	}
	for (i=1;i<6;i++)
	{
		if (i==1 && check_email($('#email'+i).value) == false)
			msg = msg + "Friend Email "+i+": is not Correct \n ";
		else if ($('#email'+i).value=="")
			continue;
		else
		{
			if (check_email($('#email'+i).value) == false)
				msg = msg + "Friend Email "+i+": is not Correct \n ";
		}
	}
	if (failed == true)
		alert(msg);
	else
		saveForm('refer',Array());	
}

function saveProject(formName,ignore,params)
{
	var savebutton = $('#'+formName+'_button');
	var savevalue = savebutton.val();
	savebutton.val( 'Saving... Please Wait');
	savebutton.attr('disabled',true);
	
	var field_name = $('#name').val();
	var field_description = $('#project_description').val();
	var project_id = $('#project_id').val();
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=saveproject&form='+formName+'&'+params,
	    type:'post',
	    data:{name: field_name,description: field_description,project_id:project_id},
        dataType: "json",
	    success: function(data){
		  alert(data.msg);
		
		  if (data.status_id==1)
		  {
		  	update_planning_project_checklist($('#project_id').val());
		  }
	      savebutton.attr('disabled', false);
	      savebutton.val(savevalue);
	     
	    }
	  });
}

function saveSignup(formName,ignore,params)
{
	var sbutton = $('#signupbutton');
	sbutton.val("Saving Signup. Please Wait...");
	//sbutton.disabled = true;
	var saveMe = JSON.stringify($('#'+formName).serializeObject());
    //var saveMe = $('#'+formName).serializeArray();
	//alert(saveMe['json']);
	$.ajax({ 
    url:'/index.php?mode=ajax&call=saveform&form='+formName+'&'+params,
    type:'post',
    data:{json: saveMe},
    dataType: "json",
    success: function(data){
      $('#problems').css('visibility',"hidden");
    	if (data.errors==1)
    	{
    	sbutton.val("Sign Up Now!");
    	window.location="#problems";
      	for ( var i2=0, len2=data.fixme.length; i2<len2; ++i2 ){
				 	$(data.fixme[i2]).css('background',"#ffd9d9");
				 	$(data.fixme[i2]).css('border',"1px solid #f99");
				}
				if (data.good.length!=0){
					for ( var i=0, len=data.good.length; i<len; ++i ){
					 $(data.good[i]).css('background',"white");
					}
				}
				//alert(data.errorpop);
				//$('problems').innerHTML = data.errormsgHTML;	
				sbutton.attr('disabled', false);
				sbutton.val('Sign Up Now');
				$('#problems').html('<strong><span style="font-size:130%;">Please Fix All Highlighed Fields</span></strong><br>'+data.errormsgHTML);
				$('#problems').css('visibility',"visible");
				
    	}
    	else
    	{
    		alert(data.savemessage);
    		document.location='/index.php?m=verify&newsignup=1';
    	}
      
    }
  });
}

function attach_project_video()
{
	var video_link = $('video_link').val();
	var provider = $('provider').val();
	if (video_link =="")
		alert("Video Url Is Empty");
	else
	{
		new Ajax.Request('/index.php?mode=ajax&call=project_video&func=add_project_video',
	  {
	    type:'post',
	    data:{video_link: video_link,provider: provider},
	    success: function(response){
    	
    	var data = response.evalJSON();
    	if (data.errors==false)
    	{

	  		var par = window.document;
				var videos = par.getElementById('videos');
				var new_div = par.createElement('div');
				new_div.id = data.id;
				if (provider=="youtube")
					new_div.innerHTML='<object width="100" height="80"><param name="movie" value="http://www.youtube.com/v/'+data.video_link+'&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+data.video_link+'&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="100" height="80"></embed></object><div id="controls_1" style="visibility:hidden;"></a>';
				if (provider=="google")
					new_div.innerHTML='<embed style="width:100px; height:80px;" id="VideoPlayback" type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docId='+video_link+'&hl=en-CA" flashvars=""> </embed>';
					
				new_div.onmouseover = function highlightme() { window.parent.document.getElementById('controls_'+data.id).style.visibility = 'visible';}
				new_div.onmouseout = function highlightme() { window.parent.document.getElementById('controls_'+data.id).style.visibility = 'hidden'; }
				var controls_new = par.createElement('div');
				controls_new.innerHTML='<div><a href="javascript:delete_project_video(\''+data.id+'\')"><img width=16 height=16 border=0 src="./images/icons/delete.png" alt="Delete Video"></div>'
				controls_new.id = 'controls_'+data.id;
				controls_new.style.visibility = 'hidden';
				new_div.appendChild(controls_new);
				videos.appendChild(new_div);
	
	  		//alert(response);
    	}
    	else
    		alert(data.errormsg);
	   }
	  }
	  )
	}
}

function delete_project_video(id)
{
	if (confirm('Are you sure?'))
	{
		var dbDelete = new Ajax.Request('/index.php?mode=ajax&call=project_video&func=delete_project_video&id='+id,'');
		document.getElementById(id).style.display = 'none';
	}
}

function deleteproject(id,name)
{
	if (confirm('*ALL PICTURES WILL BE DELETED \n *ALL DATA WILL BE DELETED \n \n Do you want to delete project '+id+'? \n Subject: '+name))
	{
	    var dbDelete = new $.ajax({ 
                        url:'/index.php?mode=ajax&call=projects&func=delete_project&projectid='+id,
	    	success: function(response){
	    		document.location="index.php?m=company";
	    	}
	    }
	    
	    );
	}
}

function ihhighlightme(id) {$('#controls_'+id).css('visibility', 'visible');}
function ihunhighlightme(id) {$('#controls_'+id).css('visibility','hidden'); }

function uploadprojectattachment()
{
	var par = window.document;
	var attachments = par.getElementById('attachments');
	var attachfile = $('#fileattachment').val();
	if (attachfile.match(".pdf") || attachfile.match(".zip") || attachfile.match(".xls") || attachfile.match(".ppt") || attachfile.match(".doc") || attachfile.match(".docx") || attachfile.match(".PDF") || attachfile.match(".ZIP") || attachfile.match(".XLS") || attachfile.match(".PPT") || attachfile.match(".DOC") || attachfile.match(".DOCX")) {
		var new_div = par.createElement('div');
		var new_img = par.createElement('img');
		new_img.src = 'images/indicator.gif';
		new_div.appendChild(new_img);
		attachments.appendChild(new_div);
		// send
		//var imgnum = images.getElementsByTagName('div').length - 1;
		var attachnum = attachments.getElementsByTagName('div').length -1;
		
		document.saveproject.attachnum.value= attachnum;
		//document.iform.imgnum.value = imgnum;
		document.saveproject.submit();
		ih_disable();
		par.getElementById('fileattachment').value = '';
	} else {
			par.getElementById('fileattachment').value = '';
			alert("File Types Allowed: .pdf .zip .ppt .doc .docx .xls");
		}

}

function uploadprojectpicture(){
	var par = window.document;
	var images = par.getElementById('images');
	var imgfile = $('#file').val();
	if (imgfile.match(".jpg") || imgfile.match(".png") || imgfile.match(".gif") || imgfile.match(".JPG") || imgfile.match(".PNG") || imgfile.match(".GIF")) {
		
		var new_div = par.createElement('div');
		var new_img = par.createElement('img');
		new_img.src = 'images/indicator.gif';
		new_div.appendChild(new_img);
		images.appendChild(new_div);
		// send
		var imgnum = images.getElementsByTagName('div').length - 1;
		$('#imgnum').val(imgnum);
		document.iform.submit();
		ih_disable();
		par.getElementById('file').value = '';
	} else {
			par.getElementById('file').value = '';
			alert("File Types Allowed: .jpg .png .gif");
		}
}

function uploadcontractorimage(){
	var par = window.document;
	var images = par.getElementById('images');
	var imgfile = $('#file').val();
	if (imgfile.match(".jpg") || imgfile.match(".png") || imgfile.match(".gif") || imgfile.match(".JPG") || imgfile.match(".PNG") || imgfile.match(".GIF")) {
		
		//var new_div = par.createElement('div');
		//var new_img = par.createElement('img');
		$("#loading_image").html( '<img src="/images/indicator.gif">');
		//new_div.appendChild(new_img);
		//images.appendChild(new_div);
		// send
		//var imgnum = images.getElementsByTagName('div').length - 1;
		//alert(imgnum);
		//document.iform.imgnum.value = imgnum;
		document.iform.submit();
		//ihc_disable();
		par.getElementById('file').value = '';
	} else {
			par.getElementById('file').value = '';
			alert("File Types Allowed: .jpg .png .gif");
		}
}

function ih_disable()
{
	$('#file').attr('disabled',true);
	$('#fileattachment').attr('disabled',true);
}

function load_city_select(toLoad)
{
  var province = $('#province_select_'+toLoad).val();
  $('#'+toLoad+'_div').html("Loading....");
	$.ajax(
	  {
	    url: '/index.php?mode=ajax&call=world&func=city_select',
        type:'post',
	    data:{sortID: toLoad,provinceID: province},
	    success: function(response){
    	
    	    $('#'+toLoad+'_div').html( response );
    	
	   }
	  }
	)	
}

function contractor_load_city_select(toLoad,type)
{
  var province = $('#province_select_'+toLoad).val();
  //$('city_'+toLoad).innerHTML = "Loading...."
	$.ajax({
	  
	    url: '/index.php?mode=ajax&call=world&func=service_area_tags',
        type:'post',
	    data:{sortID: toLoad,provinceID: province},
	    success: function(response){
    	
    	$('#serviceCitys').html(response);
    	
	   }
	  }
	)
	
}

function find_contractor_load_city_select(toLoad,type)
{
  var province = $('#province_select_'+toLoad).val();
  //$('city_'+toLoad).innerHTML = "Loading...."
	$.ajax({
      
        url: 'index.php?mode=ajax&call=world&func=find_contractor_area_tags',
	  
	    type:'post',
	    data:{sortID: toLoad,provinceID: province},
	    success: function(response){
    	
    	$('#serviceCitys').html( response);
    	
	   }
	  }
	)
	
}
function findTrade(){
	var query = $('#tradesearch').val();
	$.ajax({
      
        url: '/index.php?mode=ajax&call=trade&func=search',
	  
	    type:'post',
	    data:{query: query},
	    success: function(response){
    	
    	$('#traderesults').html(response);
    	
    	
	   }
	  }
	)
}
function findArea(countryselected){
	var query = $('#areasearch').val();
	country_id = $('#'+countryselected).prop('selectedIndex');
    //country_id = $('#'+countryselected).options[$('#'+countryselected).selectedIndex].val();
	$.ajax({
      
        url: '/index.php?mode=ajax&call=world&func=search',
	  
	    type:'post',
	    data:{query: query,country_id: country_id},
	    success: function(response){
    	
    	$('arearesults').html( response );
    	
    	
	   }
	  }
	)
}
function areaSearchRefresh()
{
	$('#reloadAreaSearcher').val("1");
}
function tradeSearchRefresh()
{
	$('#reloadTradeSearcher').val("1");
}
function areaSearch(queryField,loadName,loadDiv,size)
{
	var query = $('#'+queryField).val();
	$.ajax({ 
        url:'/index.php?mode=ajax&call=world&func=search',
	  
	    type:'post',
	    data:{query: query, loadName:loadName,size: size},
	    success: function(response){
    	
    	$('#'+loadDiv).html( response );
	   }
	  }
	)
}
function find_contractor_findTrade(){
	var query = $('#tradesearch').val;
	$.ajax({ 
        url:'/index.php?mode=ajax&call=trade&func=find_contractor_search',
	  
	    type:'post',
	    data:{query: query},
	    succuess: function(response){
    	
    	$('traderesults').html( response );
    	
    	
	   }
	  }
	)
}

function addTradeSelect(idName,selectBox)
{
	var name = $('#'+idName).val();
	var label = prompt("What Trade would you like to add?",name);
	if (label != null || label != "" || label !="null" || label != "" || label!= false)
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=trade&func=contractorAddTrade',
		    type:'post',
		    data:{label: label},
		    success: function(response){
	    	
	    	//alert(isInt(response));
	    	if (response != "false" && isInt(response)==true)
	    	{
	    		var theSel = $('#'.selectBox);
	    		theSel.options[theSel.length] = new Option(label, response);
	    		alert('Your Tag "'+label+'" was added. \n\n Please allow for up to 24 hours for full approval of the trade name.');
	    		if (selectBox == "selected")
	    			saveForm('projecttype',new Array('possible'));
	    		else if (selectBox == "selectedc")
	    			saveForm('companytype',new Array('possible'));
	    	}
	    	else
	    	{
	    		alert('Failed to add please try again.'+response)
	    	}
		   }
		  }
		)
	}
}

function addProvinceSelect(idName,selectBox)
{
	var provinces = document.getElementById(idName);

	if ($(idName) == null || $(idName)=="null" || provinces.selectedIndex==-1 || provinces.selectedIndex=="-1" )
	{
		alert("You haven't selected any options!");
	}
	else
	{
		
		var val = provinces.options[provinces.selectedIndex].value;
		var name = provinces.options[provinces.selectedIndex].text;
	
		var theSel = document.getElementById(selectBox);
		if (val != ""){
			theSel.options[theSel.length] = new Option(name, val);
			if (selectBox=="serviceselected")
				saveForm('serviceareasForm',new Array('servicepossible'));
		}
	}

}

// Save Caption for Project PICTURES

function saveCaption(id)
{
	var caption = $('caption_'+id);
	$.ajax({ 
        url:'ajax/savecaption.php',
		type: 'post',
		data: {file:id, caption:caption.value
		},
		success: function (response) {
			alert(response);
		}
	}
		
		);
	
}
// Get Caption
function getCaption(file)
{
	$.ajax({ 
        url:'ajax/getcaption.php',
		type: 'post',
		data: {	file:file },
	
		success: function(response){ return(response);}
	}
	);
}

function loadhelp(id){ //Define arbitrary function to run desired DHTML Window widget codes
	ajaxwin=dhtmlwindow.open("ajaxbox", "ajax", "/help.php?hid="+id, "", "width=450px,height=300px,left=300px,top=100px,resize=0,scrolling=1")
}

function save_new_project_status(project_id,status_id)
{
	var msg = $('#msg').val();
	
    $('#save_project_status_button').attr("disabled", true);

	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=save_new_status',
		type: 'post',
        dataType: 'json',
		data: {project_id:project_id, status_id:status_id, msg:msg},
		success: function(data){	
			
			if(data['saved']==true)
			{
				alert(data['msg']);
				document.location=data['url'];
			}
			else
			{
				$('#save_project_status_button').attr("disabled", false);
				alert(data['msg']);
				
			}
		}
	});
}

function add_project(formName)
{

	var savebutton = $('#'+formName+'_button');
	var savevalue = savebutton.val();
	savebutton.val( 'Saving... Please Wait' );
	savebutton.attr("disabled", true);
	
	var project_name = $('#new_project_name').val();
	
	if (project_name != "")
	{	
		$.ajax({ 
            url:'/index.php?mode=ajax&call=projects&func=addproject',
			type: 'post',
			data: {name:project_name},
            dataType: "json",
			success: function(data){	
				
			    //alert(data.msg);
		        savebutton.attr("disabled", false);
		        savebutton.val( savevalue );
		        document.location='index.php?m=ih&pjid='+data.projectid;
				
			}
		});
	}
	else
	{
		alert('The Project Name cannot be Empty, please type in a name');
	}
}
	
function post_project(formName)
{
	var savebutton = $('#'+formName+'_button');
	var savevalue = savebutton.val();
	savebutton.val('Saving... Please Wait');
	savebutton.attr("disabled", true);
	var project_name = $('#new_project_name').val();
	var email_address = $('#email_address').val();
		
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=postproject',
		type: 'post',
		data: {name:project_name},
        dataType: "json",
		success: function(data){	
		    alert(data.msg);
	        savebutton.attr("disabled",false);
	        savebutton.val(savevalue);
	        document.location='index.php?m=ih&pjid='+data.projectid;
			
		}
		
	})
	
}
      
 
function change_project_status(status_id)
{
	$.ajax({ 
        url: '/index.php?mode=ajax&call=projects&func=change_status',
		type: 'post',
		data: {status_id:status_id},
		dataType: "json",
		success: function(data){	
			
			var required = $('#required_msg_txt_div');
			var msg_txt = $('#required_msg_txt');
			var msg_div = $('#msg_div');

			if (data['required']=="1")
			{
				required.css("visibility",'visible');
				required.css("display", 'inline');
				msg_txt.html(data['question']);
				msg_div.html(data['content']);
			}
			else
			{
				required.css("visibility", 'hidden');
				required.css("display", 'none');
				msg_txt.html('');
				msg_div.html('');
			}
			
		}
	});
}

function resolve_project(resolved,project_id)
{
	var msg = $('#msg').val();
	
	if (resolved==0)
		var agree = confirm('Do you wish to cancel this project, because you cannot resolve the issue?');
	else
		var agree = confirm('Do you want to resolve the project, and have it resume.');
		
	if (agree == 1)
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=projects&func=resolve_project',
			type: 'post',
			data: {project_id:project_id,msg:msg,resolved:resolved},
            dataType: "json",
			success: function(data){	
				
				if(data['saved']==true)
				{
					alert(data['msg']);
					// Reload Window
					document.location.reload( true );
				}
				else
					alert(data['msg']);
			}
		});
	}
}

function accept_submitted_project(resolved,project_id)
{
	$('#confirm_submit_button').attr('disabled',true);
	var msg = $('#msg').val();
	var agree = confirm('Are you sure you want to accept the project?');
	if (agree == 1 && msg != "")
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=projects&func=accept_project',
			type: 'post',
			data: {project_id:project_id,msg:msg,resolved:resolved},
            dataType: "json",
			success: function(data){	
				
				if(data['saved']==true)
				{
					alert(data['msg']);
					document.location='/?m=myprojects&project_status=awarded&project_type=contractor#project_'+project_id;
					// Reload Window
					//document.location.reload( true );
				}
				else
				{
					$('#confirm_submit_button').attr('disabled',false);
					alert(data['msg']);
				}
			}
		});
	}
	else
	{
		alert('You are required to send the Client an acceptance message.');
		$('confirm_submit_button').attr('disabled', false);
	}
}
function award_submitted_project(resolved,project_id)
{
	$('#confirm_submit_button').attr('disabled', true);
	var msg = $('#msg').val();
	var agree = confirm('Do you want to award the project?');
	
	if (agree == 1 && msg != "")
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=projects&func=award_project',
			type: 'post',
			data: {project_id:project_id,msg:msg,resolved:resolved},
            dataType: "json",
			success: function(data){	
				
				if(data['saved']==true)
				{
					alert(data['msg']);
					document.location='/?m=myprojects&project_status=inprogress&project_type=user#project_'+project_id;
					// Reload Window
					//document.location.reload( true );
				}
				else
				{
					$('confirm_submit_button').attr('disabled', false);
					alert('Problem Awarding Project, Please Try Reloading, and submitting again!')//alert('FALSE: '+ data['msg']);
				}
			}
		});
	}
	else
	{
		alert('You are required to provide a message for the contractor.');
		$('#confirm_submit_button').attr('disabled', false);
	}
}
function refuse_project(project_id)
{
	var msg = $('#msg').val();
	
	var agree = confirm("You are about to refuse this project for the following Reason: \n "+msg+" \n\n Do you want to proceed?");
	
		
	if (agree == 1)
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=projects&func=refuse_project',
			type: 'post',
			data: {project_id:project_id,msg:msg},
            dataType: "json",
			success: function(data){	
				
				if(data['saved']==true)
				{
					alert(data['msg']);
					document.location='/my_projects/'
				}
				else
					alert("Problem Refusing Project, Please try again, or contact CCDEX.")	//alert('FALSE: '+ data['msg']);
			}
		});
	}
}

function project_to_site()
{
	var project_id = $('#project_id').val();
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=project_to_site',
		type: 'post',
		data: {project_id:project_id},
        dataType: "json",
		success: function(data){	
			if(data['saved']==true)
			{
				alert(data['msg']);
				document.location='/?m=myprojects&project_status=site&project_type=contractor'
			}
			else
			{
				alert('Could not convert project, please contact CCDEX.')//alert('FALSE: '+ data['msg']);
			}
		}
	});
}
function project_create_onsite()
{
	var name = $('#name').val()
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=project_create_onsite',
		type: 'post',
		data: {name:name},
        dataType: "json" ,
		success: function(data){	
			if(data['saved']==true)
			{
				alert(data['msg']);
				document.location='/index.php?m=ih&pjid='+data['project_id'];
			}
			else
			{
				alert('Could not create new project, contact CCDEX');//alert('FALSE: '+ data['msg']);
			}
		}
	});
}
function submit_new_project()
{
	var name = $('#name').val();
	var pre_awarded_id = $('#pre_awarded_id').val();
	
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=submit_new_project',
		type: 'post',
		data: {name:name,pre_awarded_id:pre_awarded_id},
        dataType: "json",
		success: function(data){	
			
			if(data['saved']==true)
			{
				alert(data['msg']);
				document.location='/index.php?m=ih&pjid='+data['project_id'];
			}
			else
			{
				alert('Failed to create new project, please contact CCDEX');//alert('FALSE: '+ data['msg']);
			}
		}
	});
}
function project_file_site(ftype,project_id,func,file_id)
{

	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=project_file_site',
		type: 'post',
		data: {project_id:project_id,func:func,file_id:file_id},
        dataType: "json",
		success: function(data){	
			
			if(data['saved']==true)
			{
				//alert('TRUE: '+ data['msg']);
				if (func=="add")
					switch_project_file_site(ftype,project_id,'remove',file_id);
				else if (func=="remove")
					switch_project_file_site(ftype,project_id,'add',file_id);
			}
			else
			{
				alert(data['msg']);
			}
		}
	});
}

function project_onsite_visible(project_id,visibl)
{
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=project_onsite_visible',
		type: 'post',
		data: {project_id:project_id,visible:visibl},
        dataType: "json",
		success: function(t){	
			
			if(data['saved']==true)
			{
				alert(data['msg']);
				if (visibl=="1")
					$('#'+project_id+'_project_completed_onsite_status').html("<a href=\"javascript:void(0);\" title=\"Hide Project From Your Site\" onclick=\"project_onsite_visible('"+project_id+"','0');\" >Hide From Site</a>");
				else if (visibl=="0")
					$('#'+project_id+'_project_completed_onsite_status').html("<a href=\"javascript:void(0);\" title=\"Make Project Visible On Your Site\" onclick=\"project_onsite_visible('"+project_id+"','1');\" >Make Visible</a>");
			}
			else
			{
				alert(data['msg']);
			}
		}
	});
}

function switch_project_file_site(ftype,project_id,func,file_id)
{
	
	if (ftype=="image")
	{
		if (func=="add")
		{
			$('#tosite_'+file_id).html("<img height=\"16\" width=\"16\" src=\"/images/icons/lightbulb_off.png\" title=\"Visible On Site\" onclick=\"project_file_site('image','"+project_id+"','add','"+file_id+"')\">");
			$('#'+file_id).addClass( 'floatleft project_image_onsite_no');
            $('#'+file_id).removeClass( 'project_image_onsite_yes');
		}
		if (func=="remove")
		{
			$('#'+file_id).addClass( 'floatleft project_image_onsite_yes');
            $('#'+file_id).removeClass( 'project_image_onsite_no');
			$('tosite_'+file_id).html("<img height=\"16\" width=\"16\" src=\"/images/icons/lightbulb.png\" title=\"Hide From Site\" onclick=\"project_file_site('image','"+project_id+"','remove','"+file_id+"')\">");		
		}
	}
	if (ftype=="attachment")
	{

		if (func=="add")
		{
			$('#tosite_'+file_id).html("<img height=\"16\" width=\"16\" src=\"/images/icons/lightbulb_off.png\" title=\"Visisble On Site\" onclick=\"project_file_site('attachment','"+project_id+"','add','"+file_id+"')\">");
			$('#'+file_id).addClass('attachment_file_onsite_no');
            $('#'+file_id).removeClass('attachment_file_onsite_yes');
		}
		if (func=="remove")
		{
			
             $('#'+file_id).removeClass('attachment_file_onsite_no');
            $('#'+file_id).addClass('attachment_file_onsite_yes');
			$('#tosite_'+file_id).html( "<img height=\"16\" width=\"16\" src=\"/images/icons/lightbulb.png\" title=\"Hide From Site\" onclick=\"project_file_site('attachment','"+project_id+"','remove','"+file_id+"')\">");		
		}
	}
}
function send_message()
{
	var compose_to = $('#compose_to').val();
	var compose_subject = $('#compose_subject').val();
	var compose_message = $('#compose_message').val();
	$('send_message_button').attr('disabed',true);
	var compose_conversation_id = $('#compose_conversation_id').val();
	var project_id = $("#project_id").val()
	$.ajax({ 
        url:'/index.php?mode=ajax&call=messages&func=send_message',
		type: 'post',
		data: {compose_to:compose_to,compose_subject:compose_subject,compose_message:compose_message,compose_conversation_id:compose_conversation_id,project_id:project_id},
        dataType: "json",
		success: function(data){	
			if(data['saved']==true)
			{
				//alert('TRUE: '+ data['msg']);
				alert("Message Sent!");
				document.location.reload( true );
			}
			else
			{
				$('send_message_button').attr('disabled', false);
				alert(data['msg']);
			}
		}
	});
	


}
function update_planning_project_checklist(project_id)
{
	$.ajax({ 
        url:'/index.php?mode=ajax&call=projects&func=update_planning_project_checklist',
		type: 'post',
		data: {project_id:project_id},
		success: function(data){
			$('planning_project_checklist').html(data);
		}
	});
}

function projectsmenu(num)
{
	document.getElementById('projectsmenu2').tabber.tabShow(num);
}

function composeMessage(recipient)
{
	onScreen('/index.php?mode=ajax&call=onscreen&func=compose_message&to='+recipient);
}
function composeMessageReply(conversation_id)
{
	onScreen('/index.php?mode=ajax&call=onscreen&func=compose_message&conversation_id='+conversation_id);
}
function composeMessageProject(recipient,project_id)
{
	onScreen('/index.php?mode=ajax&call=onscreen&func=compose_message&to='+recipient+'&project_id='+project_id);
}
function update_notification_to(notification_id)
{
	if (notification_id==2)
		var to =  $("#2_to").val()
	else
		var to = "";
		
		
	$.ajax({ 
        url:'/index.php?mode=ajax&call=notifications&func=update_notification_to',
		type: 'post',
		data: {notification_id:notification_id,to:to},
        dataType: "json",
		success: function(data){	
			
			if (data['saved']==true)
			{
				alert(data['msg']);
			}
			else
				alert(data['msg']);
				
				
			//alert(data['status']);
			//alert(data['verified']);
			if (data['status'] == 0)
				var check = false;
			if (data['status'] ==1)
				var check = true;
			
			//alert(data['verified']);
			
			if (data['verified']==0)
				$('#span_2_verify').css('visibility','visible');
			else
				$('#span_2_verify').css('visibility','hidden');
				
			$('#'+notification_id).attr('checked',true);
			if (notification_id==2 && data['status']==0)
				$('#'+notification_id).attr('disabled',true);
			else
				$('#'+notification_id.disabled).attr('disabled', false);
			
		}
	});
}
function notification_sms_verify()
{
	var code = $('#verify_code').val();
	
	$.ajax({ 
        url:'/index.php?mode=ajax&call=notifications&func=notification_sms_verify',
		type: 'post',
		data: {code:code},
        dataType:"json",
		success: function(data){	
			
			if (data['saved']==true)
			{
				alert(data['msg']);
			}
			else
				alert(data['msg']);
				
			if (data['verified']==0)
				$('#2').attr('disabled', true);
			else
			{
				$('#2').attr('disabled', false);
				$('#span_2_verify').css('visibility','hidden');
			}
		}
	});
	
}
function update_notification_status(notification_id,st)
{		
	$.ajax({ 
        url:'/index.php?mode=ajax&call=notifications&func=update_notification_status',
		type: 'post',
		data: {notification_id:notification_id,status:st},
        dataType: "json",
		success: function(data){	
			if (data['saved']==true)
			{
				alert(data['msg']);
			}
			else
				alert(data['msg']);
				
				
			if (data['status'] == 0)
				var check = false;
			if (data['status'] == 1)
				var check = true;
			
			
			
			$('#'+notification_id).attr('checked', check);
			
			if (notification_id==2 && data['verified']==0)
				$('#'+notification_id).attr('disabled', true);
			else
				$('#'+notification_id).attr('disabled',false);
			
		}
		
	});
}
function verify_notification(notification_id)
{
	if (notification_id==2)
	{
		$.ajax({ 
            url:'/index.php?mode=ajax&call=notifications&func=verify_notification',
			type: 'post',
			data: {notification_id:notification_id},
            dataType: "json",
			success: function(data){	
				
				
				if (data['saved']==true)
				{
					alert(data['msg']);
				}
				else
					alert(data['msg']);
					
				
				
				
			}
		});
	}
	else alert("No Beans");
}
function open_addfilter()
				{
					var par = window.parent.document;
					var filterwords = par.getElementById('filterwords');
					var filterword = $('#filterword').val()
					

				$.ajax({ 
                    url:'/index.php?mode=ajax&call=contractor_filters&func=add',
					type: 'post',
					data: {filterword:filterword},
                    dataType: "json",
					success: function(data){	
						if(data['saved']==1)
						{
							var new_filter = par.createElement('div');
							new_filter.id = "filter_"+$('filterword').val();
							var stringz = "<img src=\"./images/icons/delete.png\" onclick=\"remove_filter('filter_"+$('filterword').value+"','"+$('filterword').value+"');\"> ";
							new_filter.html( stringz + " " +$('filterword').val());
							filterwords.appendChild(new_filter);
							$('filterword').val('');
						}
						else
						{
							alert(data['msg']);
						}
					},
					onFailure: function(){ alert('Something went wrong...'); }
				});
				}
				
				function remove_filter(filterword,filtersql)
				{
					
					$.ajax({ 
                    url:'/index.php?mode=ajax&call=contractor_filters&func=remove',
					type: 'post',
					data: {filterword:filtersql},
					dataType: "json",
                    success: function(data){	
						
						if(data==1)
						{
							var par = window.parent.document;
							var filterwords = par.getElementById('filterwords');
							 
						      var len = filterwords.childNodes.length;
						      
						       for(var i = 0; i < len; i++)
						       {       
						            if(filterwords.childNodes[i].id == filterword)
						            {
						                filterwords.removeChild(filterwords.childNodes[i]);
						            }
						       }
						}
						}
					});
					
					
				}
				
function ccdex_send_message(){
	var name = $('#contact_name').val();
	var email = $('#contact_email').val();
	var subject = $('#contact_subject').val();
	var message = $('#contact_message').val();
	var department = $('#contact_department').val();
	//at=document.contact.email.value.indexOf("@")
	//period=document.contact.email.value.indexOf(".")
	var log = "The follow fields need fixing \n";
	var fail = false;
	if (name=="")
	{
		log += "Name \n";
		fail = true;
	}
	if (subject=="")
	{
		log += "Subject \n";
		fail = true;
	}
	if (email=="")
	{
		log += "Email \n";
		fail = true;
	}
	else if(check_email(email) == false)
	{
		log += "Invalid Email \n";
		fail = true;
	}
	if (message=="")
	{
		log += "Message \n";
		fail = true;
	}
	
	if (fail == true)
	{
		alert(log);
		return(false);
	}
	else
	{
		$.ajax({ 
        url:'/index.php?mode=ajax&call=ccdex&func=send_message',
		type: 'post',
		data: {email:email,name:name,department:department,subject:subject,message:message},
        dataType: "json",
		success: function(data){	
			
			if(data==1)
			{
				alert('Message Sent! Will try and get back to you within 24 hours!');
				// PAULFIX
                hideOnscren();
			}
			else
				alert('Message Failed To Send? Try emailing support@ccdex.com.');
			}
		});
		//alert('Your message was sent!');
		//document.contact.submit();
	}
}

function send_email_member(){
	var ccdex_name = $('#ccdex_name').val();
	var name = $('#contact_name').val();
	var email = $('#contact_email').val();
	var subject = $('#contact_subject').val();
	var message = $('#contact_message').val();
	
	
	var log = "The follow fields need fixing \n";
	var fail = false;
	if (ccdex_name=="")
	{
		log += "Name \n";
		fail = true;
	}
	if (name=="")
	{
		log += "Name \n";
		fail = true;
	}
	if (subject=="")
	{
		log += "Subject \n";
		fail = true;
	}
	if (email=="")
	{
		log += "Email \n";
		fail = true;
	}
	else if(check_email(email) == false)
	{
		log += "Invalid Email \n";
		fail = true;
	}
	if (message=="")
	{
		log += "Message \n";
		fail = true;
	}
	
	if (fail == true)
	{
		alert(log);
		return(false);
	}
	else
	{
		$.ajax({ 
        url:'/index.php?mode=ajax&call=ccdex&func=send_email_member',
		type: 'post',
		data: {ccdex_name:ccdex_name,email:email,name:name,subject:subject,message:message},
		success: function(data){	
			if(data==1)
			{
				alert('Email Sent!');
				//PAULFIX
                hideOnscren();
			}
			else
				alert('Email Failed To Send?');
			}
		});
		//alert('Your message was sent!');
		//document.contact.submit();
	}
}

function update_status_bar(type)
{
	$.ajax({ 
        url:'/index.php?mode=ajax&call=ccdex&func=update_status_bar',
		type: 'post',
		data: {type:type},
        dataTye: "json",
		success: function(data){	
		
			
			switch (type)
			{
				case "client":
					$('#unread_message_count').html(data['unread_message_count']);
					$('#notification_count').html(data['notification_count']);
				break;
				
				case "contractor":
					$('#unread_message_count').html(data['unread_message_count']);
					$('#notification_count').html(data['notification_count']);
					$('#open_project_count').html( data['open_project_count']);
				break;
			}
			alert('Updated!');
			}
		});
}

function signup_web_link()
{
	$('#weblink').html( $('ccdex_name').val());
}

function cs_provinces(toLoad,country_id,loadCity)
{
	country_id = $('#country_selector_'+toLoad).val();
	$('#cs_provinces_'+toLoad).html("Loading....");
	$.ajax({ 
        url:'/index.php?mode=ajax&call=world&func=cs_provinces',
	    type:'post',
	    data:{sort: toLoad, country_id: country_id, loadCity: loadCity},
	    success: function(response){
		
		$('#cs_provinces_'+toLoad).html( response );
	   }
	  }
	)	
}

function cs_cities(toLoad,province_id,type)
{
  province_id = $('#country_selector_provinces_'+toLoad).val();
  $('#cs_cities_'+toLoad).html("Loading....");
	$.ajax({ 
        url:'/index.php?mode=ajax&call=world&func=cs_cities',
	    type:'post',
	    data:{sort: toLoad,province_id: province_id,type: type},
	    success: function(response){
    	
    	$('#cs_cities_'+toLoad).html( response );
    	
	   }
	  }
	)	
}
