$(document).ready(function(){
	initRestaurantSelector();
	initNavBar();
	initHome();
	initQuickSearch();
	initSafeImagery();
	initPageTab();
	initRestaurantTabPane();
	initThumbStrip();
	initOverallRating();
	initHowRateMove();
	initRatingsBars();
	initPreventDetailClick();
	initMapColorbox();
	initExternalLinks();
	initBookmarks();
	initInlinePopups();
	
});

$(window).load(function(){
	initImageFitting();
});

function initImageFitting(){
	$(".review-right").imagefit();
}

function initBookmarks(){
	$('.bookmark_link').jFav();
}

function initInlinePopups(){
	$(".closeParent").click(function(e){
		e.preventDefault();
		$(this).parents('.inlinePopup').hide();
	});
}

function toggleInlinePopup(target) {
	$(target).toggle();
	return false;
}

function initExternalLinks(){
	$("#tourism").attr('target', '_blank');
	//$("a[@href^='http']").attr('target','_blank');
}

function initMapColorbox(){
	$('#map_larger a').click(function(e){
		e.preventDefault();
		$(this).colorbox({
			iframe: true,
			width: 1024,
			height: 600,
			scrolling: true
		});
	});
}

function initPreventDetailClick(){
	$('#restu-detail .rating ul li a, .member-right .rating ul li a').click(function(e){
		e.preventDefault();
	});
}

function initThumbStrip(){

	$(".thumbstrip img").click(function(){
		$("#mainPhoto").html("<img src='" + $(this).attr('longdesc') + "' />");
	});

}

function initHowRateMove(){
	var howRate = $('#how_to_rate_it_content').html();
	$('a#add_review').click(function(){
		$('#right_rate_it').html(howRate);
		$('#right_rate_it').show();
		$('#how_to_rate_it_content').hide();
	});
}

function initOverallRating(){
	$('#rating_experience .rev li span.light').click(function(){
		$('#rating_experience .rev li span').addClass('light');
		$(this).removeClass('light');
	});
	$('.rev li span.orange').click(function(){
		$('#rating_experience input#experience').val('3')
	})
	$('.rev li span.brown').click(function(){
		$('#rating_experience input#experience').val('2')
	})
	$('.rev li span.black').click(function(){
		$('#rating_experience input#experience').val('1')
	})
}

$(window).load(function(){
	initSafeImagery();
});

function initRestaurantTabPane(){

	$("#yellow-nav a, a#add_review").each(function(){
		$(this).click(function(e){
			e.preventDefault();
			var target ="#" + $(this).attr('id') + "_pane";
			$("#yellow-nav a, a#add_review").removeClass('active');
			$(this).addClass('active');
			$(".tabPane").hide();
			$(target).show();
		});
	});
	
	$("#venue_info").trigger('click');
	
	$("#how_to_rate_it").click(function(e){
		e.preventDefault();
		$("#right_rate_it").toggle('slow');
	});
	
	if($("#venue_promotions_pane div").length == 0){
		$("#venue_promotions").parent().remove();
	}
	
	if($("#article_thread div").length == 0){
		$("#venue_articles").parent().remove();
	}
	
	if($("#venue_branches_pane div").length == 0){
		$("#venue_branches").parent().remove();
	}
	
}


function initColumnizeArticle(){
	$('div.article:visible').columnize({columns:2, lastNeverTallest:true});
}

function initPageTab(){
	$(".paging a").each(function(i){
	
		$(this).click(function(e){
			e.preventDefault();
			window.location.hash = i+1;
			var target = i+1;
			$('div.article').hide();
			$('div.article#article' + target).show();
			
			$('div.paging > a').removeClass('active');
			$(this).addClass('active');
		});
	
	});
	
	$('a.next-page').click(function(e){
		e.preventDefault();
		var target = parseInt(window.location.hash.replace("#", '')) - 1;
		var newTarget = target + 1;
		$(".paging a:eq(" + newTarget + ")").trigger('click');
	});
	
	if(window.location.hash == ''){
		var target = parseInt(window.location.hash.replace("#", '')) - 1;
		if(target >= 1){
			$(".paging a:eq(" + target + ")").trigger('click');
		}
		
	}

}

function initSafeImagery(){

	//$('.review-right').imagefit();

}

var cf_interval = 5000;
var selected = 0;
var flip;

function crossfade(){
	var article = $("#article a");
	var total = article.length;
	
	if(selected + 1 == total){
		nextIndex = 0;
	} else {
		nextIndex = selected + 1;
	}
	
	selected = nextIndex;
	var target = ".imageSlide_" + selected + "";
	var targetSelectorText = ".textSlide:eq(" + selected + ")";
	$(".toc").removeClass('selected');
	$(".toc:eq(" + selected + ")").addClass('selected');
	crossFadeContent(target, targetSelectorText);
}

function initHome(){
	var tallest = 0;
	$("#sliderText .textSlide").each(function(){
		var height = $(this).height();
		if(height > tallest){
			tallest = height;
		}
	});
	var heightCentre = $("#slider").height() + tallest;
	$("#container .center-area .mid-col").height(heightCentre);
	$(".textSlide").each(function(i){
		$(this).slideToggle();
	});
	
	$(".toc").each(function(i){
	
		$(this).click(function(e){
			selected = i;
			clearInterval(flip);
			e.preventDefault();
			var target = "article_" + $(this).attr("id");
			var targetSelectorText = "." + target;
			$(".toc").removeClass('selected');
			$(this).addClass('selected');
			crossFadeContent("#" + target, targetSelectorText);
		});
	
	});
	
	$(".toc:eq(0)").trigger('click');
	
	//auto rotate this
	flip = setInterval("crossfade()", cf_interval);
	
}


function crossFadeContent(targetSelector, targetSelectorText){
	
	$("#sliderText .textSlide").slideUp();
	$(targetSelectorText).slideDown();
	$('.imageSlide:not("' + targetSelector + '")').fadeOut(500);
	$(targetSelector).fadeIn(1000);
}

function initNavBar(){
	if($("#subnav_about a").length > 0){
		$("#subnav_about").css('display', 'block');
	}
}

function strstr(haystack, needle, bool) {
    var pos = 0;
    
    haystack += '';
    pos = haystack.indexOf( needle );
    if (pos == -1) {
        return false;
    } else{
        if (bool){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

function buildResultsBreakdown(results, selector){
	var html = '';
	$(selector).empty();
	
	for (var x in results) {
		if(results[x] == undefined){
		
		} else {
		
			if(results[x].t > 0 && strstr(results[x].l, '%', true) == ""){
				html += "<li><a id='" + x + "' href='#'><span class='label'>" + results[x].l + "</span><span class='labelVal'>" + results[x].l2 + "</span><span class='labelTrans'>" + results[x].l3 + "</span><span class='labelSearch'>" + results[x].s + "</span> <span class='count'>(" + results[x].t + ")</span></a></li>";
				
			}
		
		}
		
	}
	$(selector).append(html);
}

function initRestaurantSelector(){
	$("input").hint();
	var animSpeed = 500;
	$("#restaurant_selector_results ul").hide();
	var filters = $("#search_filters li");
	$(filters).each(function(i){
		$("a", this).click(function(e){
			e.preventDefault();
			var target = "#" + $(this).attr('id').replace("filter_", "");
			
			if(!$(filters[i]).hasClass('active')){
			//it's open already			
				if($("#restaurant_selector_results ul:visible").length == 0){
					$(target).show(animSpeed);
				} else {
				
					$("#restaurant_selector_results ul:visible").hide(animSpeed, function(){
						$(target).show(animSpeed);
					});
				
				}
				
				$("#search_filters li a").each(function(i, filterElem){
					var target = $("#" + $(filterElem).attr('id').replace("filter_", "") + " a.chosen");
					//var target = $("#" + target + " a.chosen");
					//console.log(target.length);
					if($(target).length == 0){
						$(this).parents('li').removeClass("active");
					}
				});
				$(filters[i]).addClass('active');
			
			}
			
			
		});
	});
	
	$("#restaurant_selector_results a").live('click', function(e){
		e.preventDefault();
		$(this).parents("ul").find("a").removeClass('chosen');
		$(this).addClass('chosen');
		doLiveSearch();
	});
	
	if($("#search_query_inner li").length <= 1){
		$("#search_query_inner").hide();
	}
	
	$("#restaurant_selector_results").css('display', 'block');
	
}

function initReorderedResults(){
	$("#sorting_toolbar a").click(function(e){
		e.preventDefault();
		$("#sorting_toolbar a").removeClass('active');
		$(".sort_results_starter, .sort_results_closer, .sort_results_arrow").remove();
		$(this).addClass('active');
		$(this).parents("li").prepend("<span class='sort_results_starter'></span>");
		
		var target = $(this).attr("id");
		target = target.replace("reorder_", "");
		
		$(this).parents("li").append("<span class='sort_results_closer'></span><span class='sort_results_arrow sort_results_arrow_" + target + "'></span>");
		doLiveSearch();
	});
}

function alphaOnly(evt) 
{ 
	
    var charCode = (evt.which) ? evt.which : window.event.keyCode; 

		
    if ((charCode <= 13) || (charCode == 222) || (charCode == 46) || (charCode == 224)) 
    { 
        return true; 
    }
    else 
    { 
        var keyChar = String.fromCharCode(charCode); 
        var re = /[a-zA-Z]/ 
        return re.test(keyChar); 
    } 
}

var doLiveSearchInterval;
var dontsubmit = 0;
var searchQueryItems = Array();

function initQuickSearch(){
	
	dontsubmit = 0;
	
	$('#search_query').keyup(function(e){
		
		switch(e.keyCode){

			case 40:
				dontsubmit = 1;
				break;
				//that's down
			case 38:
				dontsubmit = 1;
				break;
				//that's down
			case 13:
				dontsubmit = 1;
			
			default:
				//nothing for now.
				dontsubmit = 0;
				break;

		}
		
		if(e.which == 13){
			//submit it
			//submitQuickSearch();
			dontsubmit = 1;
		}
		
		if(alphaOnly(e) && dontsubmit == 0){
			//delay this, we dont want to immediately search

			clearInterval(doLiveSearchInterval);
			doLiveSearchInterval = setTimeout("doLiveSearch()", 250);
		}

		
	});
	
}

var doLiveSearchInterval;
var currentlySelected = [];

function buildSearchURL(){

	searchQueryItems = '';
	currentlySelected = [];
	
	$("#search_filters li").removeClass("active");
	
	//do cuisine
	
	var cuisineSearch = $("ul#cuisine a.chosen span.labelVal").text();
	if($("ul#cuisine a.chosen span.labelSearch").text() != ""){
		cuisineSearch = $("ul#cuisine a.chosen span.labelSearch").text();
	}
	var cuisineSearchTrans = $("ul#cuisine a.chosen span.labelTrans").text();
	if(cuisineSearch != ""){
		$("#filter_cuisine").parent().addClass('active');
		searchQueryItems += "&venue_cuisine=" + cuisineSearch;
		searchQueryItems += "&venue_cuisine_=" + cuisineSearchTrans ;
		currentlySelected.push("#cuisine #" + $("ul#cuisine a.chosen").attr('id'));
	}
	
	//do district
	
	var districtSearch = $("ul#district a.chosen span.labelVal").text();
	var districtSearchTrans = $("ul#district a.chosen span.labelTrans").text();
	if($("ul#district a.chosen span.labelSearch").text() != ""){
		districtSearch = $("ul#district a.chosen span.labelSearch").text();
	}
	if(districtSearch != ""){
		$("#filter_district").parent().addClass('active');
		searchQueryItems += "&venue_district=" + districtSearch ;
		searchQueryItems += "&venue_district_=" + districtSearchTrans ;
		currentlySelected.push("#district #" + $("ul#district a.chosen").attr('id'));
	}
	
	//do food
	
	if($("ul#rating_food a.chosen").length > 0){
		var foodSearch = $("ul#rating_food a.chosen").attr('id').replace('venue_rating_food_', '');
		searchQueryItems += "&venue_rating_food=" + foodSearch ;
		currentlySelected.push("#rating_food #" + $("ul#rating_food a.chosen").attr('id'));
	}
	
	//do service
	
	if($("ul#rating_service a.chosen").length > 0){
		var serviceSearch = $("ul#rating_service a.chosen").attr('id').replace('venue_rating_service_', '');
		searchQueryItems += "&venue_rating_service=" + serviceSearch;
		currentlySelected.push("#rating_service #" + $("ul#rating_service a.chosen").attr('id'));
	}
	
	//do ambiance
	
	if($("ul#rating_ambiance a.chosen").length > 0){
		var ambianceSearch = $("ul#rating_ambiance a.chosen").attr('id').replace('venue_rating_ambiance_', '');
		searchQueryItems += "&venue_rating_ambiance=" + ambianceSearch ;
		currentlySelected.push("#rating_ambiance #" + $("ul#rating_ambiance a.chosen").attr('id'));
	}
	
	//do price
	
	if( $("ul#rating_price a.chosen").length > 0){
		var priceSearch = $("ul#rating_price a.chosen").attr('id').replace('venue_rating_price_', '');
		searchQueryItems += "&venue_rating_price=" + priceSearch ;
		currentlySelected.push("#rating_price #" + $("ul#rating_price a.chosen").attr('id'));
	}
	
	//do alfresco
	
	if($("ul#venue_al_fresco a.chosen span.label").length > 0){
		$("#filter_venue_al_fresco").parent().addClass('active');
		var alfrescoSearch = $("ul#venue_al_fresco a.chosen span.labelVal").text();
		var alfrescoSearchTrans = $("ul#venue_al_fresco a.chosen span.labelTrans").text();
		if($("ul#venue_al_fresco a.chosen span.labelSearch").text() != ""){
			alfrescoSearch = $("ul#venue_al_fresco a.chosen span.labelSearch").text();
		}
		searchQueryItems += "&venue_alfresco=" + alfrescoSearch ;
		searchQueryItems += "&venue_alfresco_=" + alfrescoSearchTrans ;
		currentlySelected.push("#venue_al_fresco #" + $("ul#venue_al_fresco a.chosen").attr('id'));
	}
	
	//do reservation
	
	if($("ul#venue_reservations a.chosen span.label").length > 0){
		$("#filter_venue_reservations").parent().addClass('active');
		var reservationSearch = $("ul#venue_reservations a.chosen span.labelVal").text();
		var reservationSearchTrans = $("ul#venue_reservations a.chosen span.labelTrans").text();
		if($("ul#venue_reservations a.chosen span.labelSearch").text() != ""){
			reservationSearch = $("ul#venue_reservations a.chosen span.labelSearch").text();
		}
		searchQueryItems += "&venue_reservations=" + reservationSearch ;
		searchQueryItems += "&venue_reservations_=" + reservationSearchTrans ;
		currentlySelected.push("#venue_reservations #" + $("ul#venue_reservations a.chosen").attr('id'));
	}
	
	//do delivery
	
	if($("ul#venue_delivery a.chosen span.label").length > 0){
		$("#filter_venue_delivery").parent().addClass('active');
		var venue_deliverySearch = $("ul#venue_delivery a.chosen span.labelVal").text();
		var venue_deliverySearchTrans = $("ul#venue_delivery a.chosen span.labelTrans").text();
		if($("ul#venue_delivery a.chosen span.labelSearch").text() != ""){
			venue_deliverySearch = $("ul#venue_delivery a.chosen span.labelSearch").text();
		}
		searchQueryItems += "&venue_delivery=" + venue_deliverySearch ;
		searchQueryItems += "&venue_delivery_=" + venue_deliverySearchTrans ;
		currentlySelected.push("#venue_delivery #" + $("ul#venue_delivery a.chosen").attr('id'));
	}
	
	//do pet friendly
	
	if($("ul#venue_pet_friendly a.chosen span.label").length > 0){
		$("#filter_venue_pet_friendly").parent().addClass('active');
		var venue_pet_friendlySearch = $("ul#venue_pet_friendly a.chosen span.labelVal").text();
		var venue_pet_friendlySearchTrans = $("ul#venue_pet_friendly a.chosen span.labelTrans").text();
		if($("ul#venue_pet_friendly a.chosen span.labelSearch").text() != ""){
			venue_pet_friendlySearch = $("ul#venue_pet_friendly a.chosen span.labelSearch").text();
		}
		searchQueryItems += "&venue_pet_friendly=" + venue_pet_friendlySearch ;
		searchQueryItems += "&venue_pet_friendly_=" + venue_pet_friendlySearchTrans ;
		currentlySelected.push("#venue_pet_friendly #" + $("ul#venue_pet_friendly a.chosen").attr('id'));
	}
	
	//do children friendly
	
	if($("ul#venue_children_friendly a.chosen span.labelVal").length > 0){
		$("#filter_venue_children_friendly").parent().addClass('active');
		var venue_children_friendlySearch = $("ul#venue_children_friendly a.chosen span.label").text();
		var venue_children_friendlySearchTrans = $("ul#venue_children_friendly a.chosen span.labelTrans").text();
		if($("ul#venue_children_friendly a.chosen span.labelSearch").text() != ""){
			venue_children_friendlySearch = $("ul#venue_children_friendly a.chosen span.labelSearch").text();
		}
		searchQueryItems += "&venue_children_friendly=" + venue_children_friendlySearch ;
		searchQueryItems += "&venue_children_friendly_=" + venue_children_friendlySearchTrans ;
		currentlySelected.push("#venue_children_friendly #" + $("ul#venue_children_friendly a.chosen").attr('id'));
	}
	
	
	if($("#sorting_toolbar a.active").length > 0){
		var sortBy = $("#sorting_toolbar a.active").attr('id');
		sortBy = sortBy.replace("reorder_", "");
	} else {
		var sortBy = "_relevancy_";
	}
	
	var cacheBuster = microtime();
	
	searchQueryItems += "&sortBy=" + sortBy + "&sortOrder=DESC" + "&cb=" + cacheBuster;
	
}

function microtime (get_as_float) {
    // http://kevin.vanzonneveld.net
    // +   original by: Paulo Freitas
    // *     example 1: timeStamp = microtime(true);
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000

    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}


function applySearchCrumbs(){
	var selectors = currentlySelected.join(',');
	if(selectors != ""){
		$(selectors).addClass("chosen");
		$(selectors).after('<a class="removeSearchTerm" href="#">X</a>');
	}
	initRemoveSearchTerms();
}

function initRemoveSearchTerms(){

	$(".removeSearchTerm").click(function(e){
		e.preventDefault();
		$(this).parent().find('a.chosen').removeClass('chosen');
		doLiveSearch();
	});
	
	$(".query_words_delete").click(function(e){
		e.preventDefault();
		var category = $(this).parents('li').attr('id');//find('a.chosen').removeClass('chosen');
		category = category.replace('query_', '');
		$("#restaurant_selector_results #" + category + " .removeSearchTerm").trigger('click');
		
		if(category == "words"){
			$("#search_query").val("");
		}
		
		//REPLACE QUERY WITH FILTER
		doLiveSearch();
	});
}

function doLiveSearch(){
	
	buildSearchURL();
	
	$('.ajaxDump').block({ 
		message: 'Loading Search Results' 
	});

	var base_url = "http://macau.womguide.com/index.php?&mode=ajax&id=5&search=";
	
	var search = encodeURIComponent($('#search_query').val());
	
	if($('#search_query').val() == $('#search_query').attr('title')){
		search = '';
	}
	
	var searchQuery = base_url + search + "&venue_district=" + searchQueryItems;

	$.get(searchQuery, function(data){
		//alert($(".ajaxDump .right-col").length);
		$('.ajaxDump').empty();
		$('.ajaxDump').append(data);
		$('.ajaxDump').unblock();
		//alert($(".right-col").length);
		initReorderedResults();
	});

}

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

/*
 * jQuery blockUI plugin
 * Version 2.09 (09/16/2008)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
    return;
}

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// plugin method for blocking element content
$.fn.block = function(opts) {
    return this.each(function() {
        if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
        if ($.browser.msie) 
            this.style.zoom = 1; // force 'hasLayout'
        install(this, opts);
    });
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
    return this.each(function() {
        remove(this, opts);
    });
};

$.blockUI.version = 2.09; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
    // message displayed when blocking (use null for no message)
    message:  '<h1>Please wait...</h1>',
    
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: { 
        padding:        0,
        margin:         0,
        width:          '160px', 
        top:            '40%', 
        left:           '35%', 
        // textAlign:      'center', 
        color:          '#fefdfb', 
        // border:         '3px solid #aaa',
        border:         'none',
        backgroundColor:'transparent',
        cursor:         'wait'
    },
    
    // styles for the overlay
    overlayCSS:  { 
        backgroundColor:'#f6f7e2', 
        opacity:        '0.6' 
    },
    
    // z-index for the blocking overlay
    baseZ: 1000,
    
    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,
    
    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,
    
    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,
    
    // fadeOut time in millis; set to 0 to disable fadeout on unblock
    fadeOut:  400,
    
    // if true, focus will be placed in the first available input field when
    // page blocking
    focusInput: true,
    
    // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
    applyPlatformOpacityRules: true,
    
    // callback method invoked when unblocking has completed; the callback is
    // passed the element that has been unblocked (which is the window object for page
    // blocks) and the options that were passed to the unblock call:
    //     onUnblock(element, options)
    onUnblock: null
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
    var full = (el == window);
    var msg = opts && opts.message !== undefined ? opts.message : undefined;
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
    var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
    msg = msg === undefined ? opts.message : msg;

    // remove the current block (if there is one)
    if (full && pageBlock) 
        remove(window, {fadeOut:0}); 
    
    // if an existing element is being used as the blocking content then we capture
    // its current place in the DOM (and current display style) so we can restore
    // it when we unblock
    if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
        var node = msg.jquery ? msg[0] : msg;
        var data = {};
        $(el).data('blockUI.history', data);
        data.el = node;
        data.parent = node.parentNode;
        data.display = node.style.display;
        data.position = node.style.position;
        data.parent.removeChild(node);
    }
    
    var z = opts.baseZ;
    
    // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
    // layer1 is the iframe layer which is used to supress bleed through of underlying content
    // layer2 is the overlay layer which has opacity and a wait cursor
    // layer3 is the message content that is displayed while blocking
    
    var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:'+ z++ +';border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
    var lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ z++ +';cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
    var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement live_search_spinner ie6htc" style="z-index:'+z+';display:none;position:absolute"><span class="live_search_spinner_animation"></span></div>');

    // if we have a message, style it
    if (msg) 
        lyr3.css(css);

    // style the overlay
    if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))) 
        lyr2.css(opts.overlayCSS);
    lyr2.css('position', full ? 'fixed' : 'absolute');
    
    // make iframe layer transparent in IE
    if ($.browser.msie) 
        lyr1.css('opacity','0.0');

    $([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
    
    // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
    var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
    if (ie6 || expr) {
        // give body 100% height
        if (full && opts.allowBodyStretch && $.boxModel)
            $('html,body').css('height','100%');

        // fix ie6 issue when blocked element has a border width
        if ((ie6 || !$.boxModel) && !full) {
            var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
            var fixT = t ? '(0 - '+t+')' : 0;
            var fixL = l ? '(0 - '+l+')' : 0;
        }

        // simulate fixed position
        $.each([lyr1,lyr2,lyr3], function(i,o) {
            var s = o[0].style;
            s.position = 'absolute';
            if (i < 2) {
                full ? s.setExpression('height','document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"')
                     : s.setExpression('height','this.parentNode.offsetHeight + "px"');
                full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                if (fixL) s.setExpression('left', fixL);
                if (fixT) s.setExpression('top', fixT);
            }
            else if (opts.centerY) {
                if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
                s.marginTop = 0;
            }
        });
    }
    
    // show the message
    lyr3.append(msg).show();
    if (msg && (msg.jquery || msg.nodeType))
        $(msg).show();

    // bind key and mouse events
    bind(1, el, opts);
        
    if (full) {
        pageBlock = lyr3[0];
        pageBlockEls = $(':input:enabled:visible',pageBlock);
        if (opts.focusInput)
            setTimeout(focus, 20);
    }
    else
        center(lyr3[0], opts.centerX, opts.centerY);
};

// remove the block
function remove(el, opts) {
    var full = el == window;
    var data = $(el).data('blockUI.history');
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    bind(0, el, opts); // unbind events
    var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);
    
    if (full) 
        pageBlock = pageBlockEls = null;

    if (opts.fadeOut) {
        els.fadeOut(opts.fadeOut);
        setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
    }
    else
        reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
    els.each(function(i,o) {
        // remove via DOM calls so we don't lose event handlers
        if (this.parentNode) 
            this.parentNode.removeChild(this);
    });
    if (data && data.el) {
        data.el.style.display = data.display;
        data.el.style.position = data.position;
        data.parent.appendChild(data.el);
        $(data.el).removeData('blockUI.history');
    }
    if (typeof opts.onUnblock == 'function')
        opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
    var full = el == window, $el = $(el);
    
    // don't bother unbinding if there is nothing to unbind
    if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) 
        return;
    if (!full) 
        $el.data('blockUI.isBlocked', b);
        
    // bind anchors and inputs for mouse and key events
    var events = 'mousedown mouseup keydown keypress click';
    b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//    var $e = $('a,:input');
//    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
    // allow tab navigation (conditionally)
    if (e.keyCode && e.keyCode == 9) {
        if (pageBlock && e.data.constrainTabKey) {
            var els = pageBlockEls;
            var fwd = !e.shiftKey && e.target == els[els.length-1];
            var back = e.shiftKey && e.target == els[0];
            if (fwd || back) {
                setTimeout(function(){focus(back)},10);
                return false;
            }
        }
    }
    // allow events within the message content
    if ($(e.target).parents('div.blockMsg').length > 0)
        return true;
        
    // allow events for content that is not being blocked
    return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
    if (!pageBlockEls) 
        return;
    var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
    if (e) 
        e.focus();
};

function center(el, x, y) {
    var p = el.parentNode, s = el.style;
    var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
    var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
    if (x) s.left = l > 0 ? (l+'px') : '0';
    if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};

})(jQuery);


(function($) {
	$.fn.imagefit = function(options) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				
					if($(img).attr('containerwidth') < $(img).attr('startwidth')){
						$(img).width('100%').each(
							function(){
								$(this).height(Math.round(
									$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
								);
							});
					} else {
						//ignore it, leave it be.
						
					}
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					$(this).attr('startwidth', $(this).width())
						.attr('containerwidth', $(container).width())
						.attr('startheight', $(this).height())
						.css('max-width', $(this).attr('startwidth')+"px");
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);

function showCoords(coords, info, ratings, showOrHide) {
	
	map.addOverlay(ew);
	coords = coords.split(",");
	
	var point = new GLatLng(parseFloat(coords[0]), parseFloat(coords[1]));
	
	
	
		if (!point) {
        		        		
        		$("#map").hide();
        		var thumbs = $(".venue_image_carousel_thumb_image");
        		if(thumbs.length == 0){
        			$("#venue_image_carousel").hide();
        		}
        		
      		} else {
      			
       			map.setCenter(new GLatLng(parseFloat(point.lat()) + 0.0023, parseFloat(point.lng()) - 0.00105 ), 17);
        		
        		
        		//var point_marked = new GLatLng(point);
      			var html = window_popup(info[0], info[1], info[2], ratings[0], ratings[1], ratings[2], ratings[3], info[3], info[4]); 
      			
      			
      			var marker = createMarker(point,html,showOrHide);
     			map.addOverlay(marker);
				
        		//marker.openInfoWindowHtml(address);
        		
    	}
      	
}

function createMarker(point,html,showOrHide) {
        var marker = new GMarker(point);
        // ========== Open the ew instead of a Google Info Window ==========
        GEvent.addListener(marker, "click", function() {
          ew.openOnMarker(marker,html);
        });
        
        if(showOrHide == "show"){
          ew.openOnMarker(marker,html);
        }
        
        return marker;
      }



function window_popup(title, url, img, food, service, ambiance, price, district, cuisine) {

		if(food != "0"){

		return '<div class="map_popup">' +
        		'<img width="65px" src="http://www.womguide.com' + img + '" />' +
				'<h3>' + title + '</h3>' +
				'<p>' + translationsCuisine + ': <span class="map_popup_p_bold">' + cuisine + '</span></p>' +
				'<p>' + translationsLocation + ': <span class="map_popup_p_bold">' + district + '</span></p>' +
				'<a class="closer" href="javascript:ew.hide()">Close</a>' +
				'<ul class="rating_gmaps_list_1">' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_food">Food:</span><span class="rating_mini_' + food + ' rating_score">' + food + '</span></li>' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_service">Service:</span><span class="rating_mini_' + service + ' rating_score">' + service + '</span></li>' +
				'</ul>' +
				'<ul class="rating_gmaps_list_2">' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_atmo">Ambiance:</span><span class="rating_mini_' + ambiance + ' rating_score">' + ambiance + '</span></li>' +
				'<li class="rating_gmaps"><span class="rating_gmaps_description_price">Price:</span><span class="rating_price_mini_' + price + ' rating_score">' + price + '</span></li>' +
				'</ul>' +
				'</div>';
		} else {
		
		return '<div class="map_popup">' +
        		'<img width="65px" src="http://www.womguide.com' + img + '" />' +
				'<h3>' + title + '</h3>' +
				'<p>' + translationsCuisine + ': <span class="map_popup_p_bold">' + cuisine + '</span></p>' +
				'<p>' + translationsLocation + ': <span class="map_popup_p_bold">' + district + '</span></p>' +
				'<a class="closer" href="javascript:ew.hide()">Close</a>' +
				'</div>';
		
		}

}

function initRatingsBars(){
	$(".review_form_rating_wrapper .rating").each(function(){
		
		$("li a", this).each(function(i){
			$(this).click(function(e){
				e.preventDefault();
				setRatingBar($(this).parents('.rating'), i);
			});
		});
	});
}

function setRatingBar(element, value){
	var realValue = value+1;
	
	if(realValue <= 3){
		var active = 'red';
	}
	
	if(realValue >=4 && realValue <= 6){
		var active = 'orange';
	}
	
	if(realValue >=7 && realValue <= 10){
		var active = 'green';
	}	
	$("li a", element).removeClass('green orange red');
	$("li a", element).each(function(i){
		if(i <= value){
			$(this).addClass(active);
		}
	});
	
	$(element).find('.num').text(realValue);
	$(element).find('.user_rating').val(realValue);
	
}

function showAddress(address, info, ratings, showOrHide) {
	
	address = cleanAddress(address);
	
	var geocoder = new GClientGeocoder();
	
	map.addOverlay(ew);
	
	geocoder.getLatLng(
		address,
		
		function(point) {
			if (!point) {
        		//show hong kong at bare min
        		//fire off an ajax request to log the error
        		
        		$("#map").hide();
        		var thumbs = $(".venue_image_carousel_thumb_image");
        		if(thumbs.length == 0){
        			$("#venue_image_carousel").hide();
        		}
        		
      		} else {
      			
       			map.setCenter(new GLatLng(point.lat() + 0.002, point.lng() - 0.001 ), 17);
        		
        		//var point_marked = new GLatLng(point);
      			var html = window_popup(info[0], info[1], info[2], ratings[0], ratings[1], ratings[2], ratings[3], info[3], info[4]); 
      			var marker = createMarker(point,html, showOrHide);
     			map.addOverlay(marker);
				
        		//marker.openInfoWindowHtml(address);
      		}
		}
	);
}

function cleanAddress(address){
	//this will make sure that 'hong kong' exists in the address
	var regEx = /Macau/;
	if(address.search(regEx) < 0){
		address = address + " Macau";
	}
	
	return address;
}

(function($){
		$.extend({
			jYoutube: function( url, size ){
				if(url === null){ return ""; }
	
				size = (size === null) ? "big" : size;
				var vid;
				var results;
	
				results = url.match("[\\?&]v=([^&#]*)");
	
				vid = ( results === null ) ? url : results[1];
	
				if(size == "small"){
					return "http://img.youtube.com/vi/"+vid+"/2.jpg";
				}else {
					return "http://img.youtube.com/vi/"+vid+"/0.jpg";
				}
			}
		})
	})(jQuery);

(function($) {
	$.fn.imagefit = function(options) {
	
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				/*
console.log($(img).attr('containerwidth') + " VS " + $(img).attr('startwidth'));
				var test = (parseInt($(img).attr('containerwidth')) < parseInt($(img).attr('startwidth')));
				alert(test);

*/					if(parseInt($(img).attr('containerwidth')) < parseInt($(img).attr('startwidth'))){
						
						$(img).width('100%').each(
							function(){
								$(this).height(Math.round(
									$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
								);
								
							});
					} else {
						//ignore it, leave it be.
					}
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					$(this).attr('startwidth', $(this).width())
						.attr('containerwidth', $(container).width())
						.attr('startheight', $(this).height())
						.css('max-width', $(this).attr('startwidth')+"px");
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);


eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(7($){$.8.9=7(d){g e=$.v({},$.8.9.k,d);g f=e.l;2.w(7(){5(!$(2).3(\'4\')||$(2).3(\'4\')=="#"){$(2).3(\'4\',j.x.4)}5(!$(2).3(\'6\')){$(2).3(\'6\',y.6)}5($.h.z){$(2).3(\'m\',$(2).3(\'4\')).3(\'4\',\'\').3(\'4\',\'A:B(0)\').3(\'C\',\'$.8.9.n(2,"\'+$(2).3(\'6\')+\'","\'+$(2).3(\'m\')+\'")\')}i{$(2).o(p)}});7 p(a){g b=$(2).3(\'4\');g c=$(2).3(\'6\');b=b.E("q:///","F://q/");5($.h.G){j.H.I(b,c)}i 5($.h.J){j.r.K(c,b,\'\')}i 5(L.M.N().O(\'P\')>-1){s(f)}i 5($.h.Q){s(f)}a.R()};t 2};$.8.9.k={l:\'S "T + D" U "V + D" W X, u Y 2 Z u 10 11.\'};$.8.9.n=7(e,a,b){e.12="r";e.6=a;e.4="";e.4=b;e.o();t 13}})(14);',62,67,'||this|attr|href|if|title|function|fn|jFav|||||||var|browser|else|window|defaults|msg|link|OperaBookmark|click|addToFavorites|file|sidebar|alert|return|to|extend|each|location|document|opera|javascript|void|onClick||replace|http|msie|external|AddFavorite|mozilla|addPanel|navigator|userAgent|toLowerCase|indexOf|chrome|safari|preventDefault|Press|Ctrl|or|CMD|for|MAC|add|page|your|bookmarks|rel|false|jQuery'.split('|'),0,{}))
