// JavaScript Document
$(document).ready(function() {
						   
		//alert('ready');
	
		$("#all_states").load("/ajax/allStates.php");
		
		$(".toggle_spec").children("ul").hide();
		$("#quote_btn").next("div").hide();
		//$("#joboffercontacts").hide();
		
		$(".state_selector_btn").hover(function() {
			var pos = $(this).position();
			var w = $("#all_states").width();
			$("#all_states").css("top", pos.top + 26 + "px");
			$("#all_states").css("left", pos.left - w/2 + "px");
			$("#all_states").fadeIn("slow");
		}, function() {
			$("#all_states").hide();
		});
		
		$("#all_states a").live('click', function() {
			var state = $(this).attr("rel");
			$.post('/ajax/select_state.php', { state: state }, function() {
				window.location.reload();															
			});
		});
		
		$("li.toggle_spec").click(function() {
			$(this).children(".spec").toggle("slow");
		});
		
		$("a#showjoboffercontacts").click(function() { 
			$("div#joboffercontacts").slideToggle("slow"); 
		});
		
		$("a.group").fancybox({ 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true, 'centerOnScroll': false });

		$("div.jobofferfoto").hover(function() {
			var key = $(this).attr("rel");
			$(this).append('<a href="#" class="deljobofferfoto" title="delete this photo" onclick="if(confirm(\'Really delete this photo?\')) { window.location = \'/cabinet/joboffers/deletejobofferphoto.php?id=' + key + '\'; }"></a>');
			var pos = $(this).position();
			var w = $(this).width();
			$(".deljobofferfoto").css("top", pos.top + 15 + 'px');
			$(".deljobofferfoto").css("left", pos.left + w - 27 - 5 + 'px' ); 
		}, function() { $(".deljobofferfoto").remove(); });
		
		$("div.projectfoto").hover(function() {
			var key = $(this).attr("rel");
			$(this).append('<a href="#" class="delprojectfoto" title="delete this photo" onclick="if(confirm(\'Really delete this photo?\')) { window.location = \'/cabinet/projects/deleteprojectphoto.php?id=' + key + '\'; }"></a>');
			var pos = $(this).position();
			var w = $(this).width();
			$(".delprojectfoto").css("top", pos.top + 15 + 'px');
			$(".delprojectfoto").css("left", pos.left + w - 27 - 5 + 'px' ); 
		}, function() { $(".delprojectfoto").remove(); });
		
		
		$(".jobofferfotosprev").hover(function() {
			var pos = $(this).position();
			$(this).next("div").css('left', (pos.left + 20) + 'px');
			$(this).next("div").css('top', (pos.top) + 'px');
			$(this).next("div").slideDown("slow");										  
		}, function() {
			$(this).next("div").fadeOut("fast");
		});
		
		$("div.jobofferdelete").click(function() {
			if(confirm('Do you really want to delete this job offer?')) {
				var jobofferid = $(this).attr("rel");
				$.post('/ajax/jobofferdelete.php', { jobofferid: jobofferid }, function(data) { $("div#joboffers").html(data); });	
			}								   
		});
		
		$(".jobofferclosebutton").live('click', function() { 
			if(confirm('Do you really want to close this job offer?')) {
				var jobofferid = $(this).attr("rel");
				$(this).prevAll(".jobofferstatus").attr("id", "selectedjoboffer");
				$.post('/cabinet/ajax/jobofferstatus.php', { jobofferid: jobofferid, action: 'close' }, function(data) {																		
					if(data) {
						js_notifier('Job offer has been closed!');
						$("#selectedjoboffer").html(data);
						$(".jobofferstatus").removeAttr("id");
					}
				});
				$(".hireContractor").each(function() {
					$(this).fadeOut('fast');
				});
			}
		});
		
		$(".jobofferopenbutton").unbind().click(function() {
			if(confirm('Do you really want to reopen this job offer?')) {
				var jobofferid = $(this).attr("rel");
				$(this).prevAll(".jobofferstatus").attr("id", "selectedjoboffer");
				$.post('/cabinet/ajax/jobofferstatus.php', { jobofferid: jobofferid, action: 'open' }, function(data) {
					if(data) {
						js_notifier('Job offer has been opened!');
						$("#selectedjoboffer").html(data);
						$(".jobofferstatus").removeAttr("id");
					}
				});
			}
		});
		
		
		$(".notifier").hide();
		var w = $(window).width();
		var scrolltop = $(window).scrollTop();
		var h = $(window).height();
		$(".notifier").css("top", (scrolltop + h/2 - $(".notifier").height()/2) + "px");
		$(".notifier").css("left", (w/2 - $(".notifier").width()/2) + "px");
		$(".notifier").fadeIn("slow");
		//setTimeout(function() { $(".notifier").fadeOut("slow"); setTimeout(function() { $(".notifier").remove(); }, 500); }, 5500);
		
		$(".department_states").click(function() {
			var checkbox = $(this);
			var status = checkbox.attr("checked");
			if(status) {
				var state = checkbox.attr("rel");
				$.post("/ajax/loadcities.php", {state: state}, function(data) {
					checkbox.next().next().html(data);
				});
				checkbox.next().next().slideDown('slow');
			} else {
				$(this).next().next().slideUp('slow');	
			}
		});
		
		$(".department_spec").click(function() {
			var this_checkbox = $(this);
			var target_div = $(this).next().next();
			var status = this_checkbox.attr("checked");
			if(status) {
				target_div.slideDown('slow');	
			} else {
				target_div.slideUp('slow');	
			}
		});
		
		$("#department_nationwide").click(function() {
			var this_checkbox = $(this);
			var target_div = this_checkbox.next("div");
			var status = this_checkbox.attr("checked");
			if(status) {
				target_div.slideUp('slow');
			} else {
				target_div.slideDown('slow');	
			}									   
		});
		
		$(".all_cities").click(function() {
			var this_checkbox = $(this);
			var target_div = this_checkbox.next("div");
			var status = this_checkbox.attr("checked");
			//alert(status);
			if(status) {
				//target_div.hide();
				target_div.slideUp('slow');
			} else {
				target_div.slideDown('slow');
			}									   
		});
		
		$(".state_selector").change(function() {
			var state = $(this).val();
			$.post('/ajax/loadcitiestoselector.php', { state: state }, function(data) {
				$("#city_selector").html(data);																
				$("#city_selector").removeAttr("disabled");
			});
		});
		
		$("#quote_btn").click(function() {
			$(this).next("div").slideToggle("fast");						   
		});	
		
		
		if(!($("input[name=uzip]").val()))
		{
			$("input[name=uzip]").val('any');
		}
		$("input[name=uzip]")
			.focusin(function()
				{
					if($(this).val() == 'any')
					{
						$(this).val('');
					}
				})
			.focusout(function()
				{
					if($(this).val() == '')
					{
						$(this).val('any');
					}
				});
			
		
		/* $("#send_quote").click(function() {
			var div = $(this).parent().parent().parent();
			var joboffer_id = $("input[name=joboffer_id]").val();
			var quote_bid = $("input[name=quote_bid]").val();
			var quote_message = $("textarea[name=quote_message]").val();
			$.post("/cabinet/ajax/sendquote.php", {joboffer_id : joboffer_id, quote_bid: quote_bid, quote_message: quote_message}, function(data) {
				div.html(data);																																   			});
		}); */
		
		$(".hire_btn").click(function() {
			var json = $(this).attr("rel");
			$.post("/cabinet/ajax/hire.php", { json: json}, function(data) {
				$("#candidates").hide();
				$("#candidates").html(data);
				$("#candidates").fadeIn('slow');
			});
		});
		
//		var $quoteForm = $('<div></div>')
//							.html($("#quoteForm").html())
//							.dialog({
//								autoOpen: false,
//								title: 'Basic Dialog'
//							});
//		$("#makeQuote")
//				.click(function() {
//					$quoteForm.dialog('open');
//				});
		$(".hireContractor").live('click', function() {
			var json = $(this).attr('rel');
			var resultBlock = $(this).parent().parent();
				resultBlock.html('<div style="text-align:center;overflow:hidden;"><img src="/images/ajax-loader.gif" /></div>');
				$.post("/cabinet/ajax/hire.php", {json: json}, function(data) {
						resultBlock.html(data);
				});
			$(".hireContractor").each(function() {
				$(this).fadeOut('fast');
			});
		});
		$(".deleteFeedback").click(function() {
			if(confirm("Do you really want to delete this your feedback?")) {
				var feedbackBlock = $(this);
				var feedback = feedbackBlock.attr("id");
				feedbackInfo = feedback.split('_', 2);
				$.post('/ajax/deleteFeedback.php', {feedbackID: feedbackInfo[1]}, function(data) {
					if(data) {
						feedbackBlock.parent().parent().fadeOut("slow");
					}
				});
			}
		});
		
	
		$(".mapBlock").each(function() {
			var address = $(this).attr("id");
			showMap(address, this);
		});
		
		$(".helpQuestion").click(function() {
			var answerBlock = $(this).next();
			var displayAttr = answerBlock.css('display');
			if(displayAttr == 'none') {
				answerBlock.slideDown('fast');
			} else {
				answerBlock.slideUp('fast');
			}
		});
		
		getAnswer();
		
		$(".editQuote").live('click', function() {
			var quoteJSON = $(this).attr('rel');
			var resultBlock = $(this).parent().parent();
				resultBlock.html('<div style="text-align:center;overflow:hidden;"><img src="/images/ajax-loader.gif" /></div>');
			$.post('/ajax/editQuote.php', {quoteJSON: quoteJSON}, function(data) {
				resultBlock.css('text-align', 'left');
				resultBlock.html(data);
			});
		});
		
		$(".sendMessage").live('click', function() {
			var quoteJSON = $(this).attr('rel');
			var resultBlock = $(this).parent().parent();
				resultBlock.html('<div style="text-align:center;overflow:hidden;"><img src="/images/ajax-loader.gif" /></div>');
				$.post('/ajax/sendMessage.php', {quoteJSON: quoteJSON}, function(data) {
					resultBlock.css('text-align', 'left');
					resultBlock.html(data);
				});
		});
		
		$(".cancelForm").live('click', function() {
			var quotejson = $(this).attr("rel");
			var resultBlock = $(this).parent().parent().parent().parent().parent().parent().parent().parent();
				resultBlock.html('<div style="text-align:center;overflow:hidden;"><img src="/images/ajax-loader.gif" /></div>');
				$.post('/cabinet/ajax/cancelForm.php', {quotejson: quotejson}, function(data) {
					resultBlock.css('text-align', 'right');
					resultBlock.html(data);
				});
		});

});

	function showMap(address, element) {
		if(!address) return;
			geocoder = new google.maps.Geocoder();
			geocoder.geocode({ 'address': address }, function(results, status) {
				
			 	var lat = results[0].geometry.location[0];
			    var lng = results[0].geometry.location[1];
				alert(lng);
			    var latlng = new google.maps.LatLng(lat, lng);
				var myOptions = {
					      zoom: 11,
					      center: latlng,
					      mapTypeControl: false,
					      mapTypeId: google.maps.MapTypeId.ROADMAP
				}
				map = new google.maps.Map(element, myOptions);
				var marker = new google.maps.Marker({
		              map: map, 
		              position: results[0].geometry.location
		        });
			});
	}

/* 
function showAddress(response) {
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
    marker = new GMarker(point);
    map.addOverlay(marker);
    marker.openInfoWindowHtml(
        '<b>orig latlng:</b>' + response.name + '<br/>' + 
        '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
  }
} */

	function getAnswer() {
		if(window.location.pathname.match('^\/help')) {
			var pathParts = String(window.location).split('#', 2);
				if(pathParts[1]) {
					$("#" + pathParts[1]).children(".helpAnswer").slideDown('fast');
				}
		}
	}
	
	function js_notifier(str) {
		$(document.body).append('<div class="js_notifier" style="position:absolute; width:300px; padding:20px 20px; background-color:#fff; border:solid 1px #cacaca; z-index:10; display:none; text-align:center; background-color:#fdff63;">' + str + '</div>');
		var w = $(window).width();
		var scrolltop = $(window).scrollTop();
		var h = $(window).height();
		$(".js_notifier").css("top", (scrolltop + h/2 - $(".js_notifier").height()/2) + "px");
		$(".js_notifier").css("left", (w/2 - $(".js_notifier").width()/2) + "px");
		//$(".js_notifier").animate( {"top": "-=30px" }, 1500 );
		$(".js_notifier").fadeIn("slow");
		setTimeout(function() { $(".js_notifier").fadeOut("slow"); setTimeout(function() { $(".js_notifier").remove(); }, 500); }, 1500);
	}

	function replyform(id) { 
		$.post('/ajax/loadreplyform.php', { id: id}, function(data) { $("div#replyform").html(data); }); 
	}
	
	function select_state(state) { 
		$.post("/ajax/select_state.php", { state: state }, function(data) { $("#state").html(data); location.reload(); });	
	}
	
	function select_state_form() { 
		$("#state p.selected").load("/ajax/select_state_form.php");
	}
	
	function load_address(id) {
		$.post("/cabinet/ajax/load_address.php", { id: id }, function(data) { $("#address_info").html(data); });
	}
	
