jQuery(document).ready(function($){
	/* ==================================== */
	/* Search fields - Dropdown suggestions */
	/* ==================================== */
	jQuery.fn.extend({
		omgsuggestion: function(options) {
			var prevlength = 0;
			var hasSelected = false;
			
			return this.each(function(){
				var $input = $(this);
				var timeout = false;
	
				var $ulBox = $("<ul></ul>");
	
				$ulBox.addClass('suggestionbox');
				$ulBox.css({position:'absolute',zIndex:999999999,overflow:'auto'});
				$ulBox.attr({id:'suggestionbox-'+ $input.attr('name')});
				$ulBox.appendTo('body').hide();
				
				$ulBox.scrollLeft = 1;
				
				// on focus				
				$input.bind('focus', function(evt){
					var w = $input.outerWidth();
	
					var input_h = $input.outerHeight();
					var input_position = $input.offset();
					
					$ulBox.css({width: w, top: input_position.top + input_h, left: input_position.left});
					
					if ($('li', $ulBox).length >= 1) {
						$('li', $ulBox).removeClass('selected');
					}
				});
				
				// out of focus
				$input.bind('blur', function(evt){
					setTimeout(function(){
						$ulBox.slideUp(50);
					}, 100);
				});
	
				// key presses
				$input.bind('keydown', function(evt){
					switch (evt.which) {
						case 37: 
						case 39:
							// left and right keys
							break;
						case 38:
							// up key
							evt.preventDefault();
							//$ulBox.slideUp(50);
							
							var lastselected = $('li.selected', $ulBox);
							var nextselected = lastselected.prev(":not(.error)");
							if (nextselected.size() == 1) {
								$('li', $ulBox).removeClass('selected');
								nextselected.addClass('selected');
							}
							hasSelected = false;
							break;
						case 40:
							// down key
							evt.preventDefault();
							$ulBox.slideDown(25);
							
							var lastselected = $('li.selected', $ulBox);
							if (lastselected.size() == 0) {
								var nextselected = $("li:first:not(.error)", $ulBox);
							} else {
								var nextselected = lastselected.next(":not(.error)");
							}
							
							if (nextselected.size() == 1) {
								$('li', $ulBox).removeClass('selected');
								nextselected.addClass('selected');
							}
							hasSelected = false;
							break;
						case 9:
							// tab key
							var currentselected = $('li.selected:not(.error)', $ulBox);
							if (currentselected.size() == 1) {
								$input.val($.trim(currentselected.text()));
								$ulBox.slideUp(50);
							}
							break;
						case 13:
							// enter key
	
							var currentselected = $('li.selected:not(.error)', $ulBox);
	
							if ($input.val() != '' && currentselected.size() == 0) {
								hasSelected = true;
							}
							if (currentselected.size() == 1) {
								$input.val($.trim(currentselected.text()));
								$ulBox.slideUp(50);
								hasSelected = true;
							}
	
							if (!hasSelected){
								evt.preventDefault();
							}
	
							break;
						case 27:
							// escape key
							$ulBox.slideUp(50);
							break;
						default:
							// other keys
							var srchval = $.trim($input.val());
							if (srchval.length != prevlength) {
								if (timeout){ clearTimeout(timeout); }
								timeout = setTimeout(ajax_search, 300);
								prevlength = $.trim($input.val()).length;
							}
							break;
					} // end switch
				});
				
				var ajax_search = function() {
					var srchval = $.trim($input.val());
					$.ajax({url: options.url, data: {search:srchval}, dataType:'json', success: ajax_callback});
				};
				
				var ajax_callback = function(data) {
					var li = "";
					for (var i = 0; i < data.length; i++) {
						li += '<li><a href="#">' + data[i].option + '</a></li>';
					}
					if (data.length <= 0) {
						li = '<li class="error">There are no results found</li>';
					}
					$ulBox.html(li).slideDown(10);
					
					$("li:not(.error) a", $ulBox).each(function(){
						var $li = $(this);
						$li.bind("mousedown", function(){
							$input.val($.trim($li.text()));
							$input.focus();
							$ulBox.slideUp(50);
						}).click(function(evt) {
							evt.preventDefault(); 
							return false;}
						);
					});
				};
	
			});
		}
	});


	/* ================ */
	/* global JS object */
	/* ================ */
	var omgGlobalJS = function() {
		return{
			/************************
				Init function
				-- attach event handlers
				-- fire drop down menu if present
				-- country select disable for forms
			************************/
			init: function(){
				// drop down menus if LI has UL menu will fire
				if ($("#navigation-items") != null) {
					$("#navigation-items").children("li").hover(
						function(){
							$(this).children("ul").show();
							if($(this).children("ul").children("li").children("ul")){
								$(this).children("ul").children("li").hover(
									function(){
										$(this).children("ul").show();
									},
									function(){
										$(this).children("ul").hide();
									}
								);
							}
						},
						function(){
							$(this).children("ul").hide();
						});
				}
				// end drop down
				
				//network nav handler
				if ($("#omg-network-nav-btn") != null) {
					$("#omg-network-nav-btn").click(this.networkNav);
				}
				
				//generic contact form country handler Aus + Nz
				if ($("#cf-country") != null) {
					$("#cf-country").change(function () {
						  $("#cf-country option:selected").each(function () {
							  var stateTxt = $(this).val();
								if(stateTxt == "Australia"){
									$("#cf-state").removeAttr("disabled");
								} else{
									$("#cf-state").attr("disabled", true); 
								}
							  });
						}).trigger('change');
				}
				//generic contact form handler
				if ($(".cf-submit") != null) {
					$(".cf-submit").click(this.contactForm);
				}
			},
			// end init
			/************************
				contact form validation
				-- fire on submit click
				-- highlight required field labels
			
			************************/		
			contactForm: function(e){
				//stop form submission
				e.preventDefault();
				//check required fields
				var reqFields = $(".cf-required").length;
				var reqFieldsCount = 0;
				$(".cf-error > ul").html("");
				$(".cf-required").each(function(i){
					var fail = false;
					if($(this).attr("type") == "checkbox" && $(this).attr("checked") == false) {
						fail = true;
					} else if($(this).val() == ""){
						fail = true;
					}
					if(fail) {
						$(this).parent().children().children("strong").css("color","#cc0000");
						var fieldText = $(this).parent().children().children("strong").text();
						if(fieldText == "") {
							fieldText = $(this).attr("name");
							fieldText = fieldText.replace("data[", "");
							fieldText = fieldText.replace("]", "");
						}
						$(".cf-error > ul").append("<li>"+ fieldText.split(":", 1) +"</li>");
					} else {
						$(this).parent().children().children("strong").css("color","#000");
						reqFieldsCount++;
					}
				})
				//final check then give a response
				if(reqFieldsCount == reqFields){
					// submit the form
					$("#contact-form-container form").submit();
					
					$(".cf-error").hide();
				} else {
					$(".cf-error").fadeIn();
					window.location.href="#contact-form-top";
				}
			},
			/************************
				network nav open close
				-- fire on link click
				-- slide open panel
				-- switch open/close arrow class
			
			************************/
			networkNav : function(e){
				e.preventDefault();
				if($(this).hasClass("btn-open")){
					$(this).removeClass("btn-open");
					$(this).addClass("btn-closed");
				}else{
					$(this).removeClass("btn-closed");
					$(this).addClass("btn-open");				
				}
				$("#omg-network-nav ul").slideToggle("normal");
			}
		 }
	}();

	/* generic get cookie lookup */
	function getCookie(name) {
		if (document.cookie.length>0) {
			start = document.cookie.indexOf(name + "=");
			if (start != -1) {
				start = start + name.length + 1;
				end = document.cookie.indexOf(";",start);
				if (end == -1) {
					end = document.cookie.length;
				}
				return unescape(document.cookie.substring(start,end));
			}
		}
		return "";
	}

	/* generic set cookie */
	function setCookie(name, value, expiryday) {
		var expirydate = new Date();
		expirydate.setDate(expirydate.getDate() + expiryday);
		document.cookie = name + "=" + escape(value) + ((expirydate==null)?"":";expires=" + expirydate.toGMTString());
	}

	omgGlobalJS.init();

	/* find by map button */	
	$(".find-by-map .button").bind("click", function() {
		$(".find-by-map .map").toggle("fast");
	});
	
	$("form[name*=form_search]").each(function(){
		var $form = $(this);
		var $inp_category = $(":input[name*=text_47]", $form);
		var $inp_location = $(":input[name*=text_57]", $form);
		var $btn_submit = $(":submit[name*=submit]", $form);
		
		var $init_cat_val = $.trim($inp_category.val());
		var $init_loc_val = $.trim($inp_location.val());
	});
	
	// do autocomplete (suggested text)
	$(":input[class*=predictive_category]").omgsuggestion({
		url: '/static/predictive/category.php',
		dataType: 'json',
		text: 'Type to search for category'
	});
	
	$(":input[class*=predictive_location]").omgsuggestion({
		url: '/static/predictive/search.php',
		dataType: 'json',
		text: 'Type to search for location'
	});
	
	//show phone number button
	$("a.showphone").each(function() {
		$(this).bind("click", function(event) {
			var $phone_box = $(this).parent();
			listing_id = $(this).attr("id").substring(3, $(this).attr("id").length);
			if ($(".phone-number", $phone_box).is(":visible")) {
				$("span.click_txt", $phone_box).html("Show Phone Number");
				$(".phone-number", $phone_box).hide("fast");
			}
			else {
                var add_loc = $('#additional_location_' + listing_id).text();
                var add_uri = '';
                if (add_loc > 0) {
                    add_uri = '&additional_loc_id='+add_loc
                }
				$.getJSON("http://" + location.hostname + "/static/secure_omg/businesslisting_details.php?data_type=phone&id=" + listing_id + add_uri,
					function(data){
						if (typeof(data) != 'undefined') {
							if (data.phone != "") {
								$("p.phone", $phone_box).html(data.phone);
								$("span.click_txt", $phone_box).html("Hide Phone Number");
								$(".phone-number", $phone_box).show("fast");
							}
							if (data.tracking != "") {
								$(".tracking", $phone_box).html('<img width="0" height="0" src="http://tracker.omg.com.au/' + data.tracking + '" />');
							}
						}
					}
				);
			}
			event.preventDefault();
		});
	});
    if($('.yahoo_ads').length > 0) {
        // quotes suck in the adds
            $('.yahoo_ads').append($('#listings').html());
            $('#listings').html('');
            $('.yahoo_ads small').append('<div style="clear:both;margin-bottom:10px"></div>');
                
            $('.yahoo_ads').append('<div style="clear:both;margin-bottom:10px"></div><hr />');
    }
});

function adfeed_loadfeed(nmc_id) {
    var url = document.location.href;
    if(url.indexOf('?') != -1) {
        url += '&nmc=' + nmc_id;
    } else {
        url += '?nmc=' + nmc_id;
    }
    
    $('#ad-nmc-'+nmc_id).load(url, function() {
        if(typeof swap_cpc_listings == 'function') {
            swap_cpc_listings('ad-nmc-'+nmc_id);
        }
    });        
}
