$(document).ready(function(){

	$(".pagination-control > li > a").smoothScroll();
	$(".smoothScroll").smoothScroll();

	$(".thermotip").tipsy({gravity: $.fn.tipsy.autoWE});

    $("#dis_show_more").click(function(e){
        e.preventDefault();
        $("#dis_hidden").slideDown(100);
        $(this).hide();
    });

    $("#review_show_more").click(function(e){
        e.preventDefault();
        $("#review_ellipsis").hide();
        $("#review_hidden").show();
        $(this).hide();
    });

    $("#like").bind('click', like);
    $("#dislike").bind('click', like);

    bindMenuFlipHandler();
    bindKeyboardMenuNav();

    // SMS
	function closeSMSPopup(event)
	{
		if(event.type == 'click' || event.keyCode == 27)
		{
			$("#sms_dis_id").val('');
			$("#sms_popup").fadeOut(150);
			$(document).unbind('click keypress', closeSMSPopup);
			return false;
		}
	}

    $("a.sms_get").click(function(){
        var dis_id = this.id.substr(4);
        $("#sms_submit").val("Send").attr("disabled", "");
        $("#sms_mobile").val("");
        $("#sms_message").html("");
        $("#sms_dis_id").val(dis_id);
        $("#sms_title").html('Get <b>"'+$("#dis_title_"+dis_id).text().substr(0, 20)+'..."</b> on your mobile.');
        $("#sms_popup").css("left", $(this).offset().left - $("#sms_popup").width()/2)
                        .css("top", $(this).offset().top + 20)
                        .fadeIn('fast', function(){$("#sms_mobile").focus();});
		$(document).bind('click keypress', closeSMSPopup);
		return false;
    });
	$("#sms_popup").click(function(){ return false; });
    $("#sms_close").click(closeSMSPopup);
    $("#sms_submit").click(function(){
        if($("#sms_mobile").val().match('[0-9]{10}'))
        {
            $("#sms_submit").val("Sending...").attr("disabled", "disabled");
            $.get(HOST+'php/sms_process.php?ph='+$("#sms_mobile").val()+'&did='+$("#sms_dis_id").val(),
                function(data){
                    $("#sms_message").text(data.replace(/^\s\s*/, '').replace(/\s\s*$/, '').substring(0, 100));
                    setTimeout(function(){$("#sms_close").trigger('click');}, 5000);
                });
        }
        else
            $("#sms_message").text("Invalid mobile number!");
    });

	addReviewEvents();
	initRatingWidget();

    // This should be last
    if(document.getElementById("map_canvas"))
        loadMap();
});

function initMap(){
    var latlng = new google.maps.LatLng(mapData.lat, mapData.long);
    var myOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: mapData.title
    });
    var infowindow = new google.maps.InfoWindow({
        content: mapData.infoContent
    });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
    // infowindow.open(map, marker);
};

function bindKeyboardMenuNav()
{
    $(document).keypress(function(e){
        if (!$(e.target).is('input, textarea')) {
            if(e.keyCode == 39)
                $("#menuPaginationTop > ul > li.current").next("li.active").children("a").trigger("click");
            else if(e.keyCode == 37)
                $("#menuPaginationTop > ul > li.current").prev("li.active").children("a").trigger("click");
        }

    });
}

function bindMenuFlipHandler()
{
    $("#menuPaginationTop > ul > li > a, #menuPaginationBottom > ul > li > a").click(function(e){
        e.preventDefault();

		// track page view in analytics
		_gaq = _gaq || [];
		_gaq.push(['_trackPageview', '/menuPageFlip/'+RES_ID], ['t2._trackPageview', '/menuPageFlip/'+RES_ID]);

        // Change paginators
        var pagination = '<ul class="pagination-control">';
        var page = ($(this).attr("href").match(/page=[0-9]+/)+'').substring(5);
        var num = $("#menuPaginationTop > ul > li").length - 2;
        if(page > num)
            page = num;
        if(page <= 1)
        {
            page = 1;
            pagination += '<li class="disabled">&laquo; Previous</li>';
        }
        else
            pagination += '<li class="active"><a href="'+$(this).attr("href").replace(/page=[0-9]+/, 'page='+(page-1))+'">&laquo; Previous</a></li>';
        for(var i=1; i<=num; i++)
        {
            if(i != page)
                pagination += '<li class="active"><a href="'+$(this).attr("href").replace(/page=[0-9]+/, 'page='+i)+'">'+i+'</a></li>';
            else
                pagination += '<li class="current">'+i+'</li>';
        }
        if(page >= num)
            pagination += '<li class="disabled">Next &raquo;</li>';
        else
            pagination += '<li class="active"><a href="'+$(this).attr("href").replace(/page=[0-9]+/, 'page='+(parseInt(page)+1))+'">Next &raquo;</a></li>';

        $("#menuPaginationTop, #menuPaginationBottom").html(pagination+'</ul>')
        bindMenuFlipHandler();

		$("#menuLoading").slideDown();

        // Load next image by ajax
        $.ajax({
            type: "GET",
            url: HOST+"php/getNewMenuImage.php",
            data: "city="+cityId+"&menu="+menuId+"&page="+page,
            dataType: "json",
            success: function(msg){
                if(msg['status'] == 'success' && msg['now'] != 'none')
                {
                    var I = new Image();
                    $(I).load(function(){
		 				$("#menuLoading").slideUp();
					
                        var alt = $("#menuContainer > img").attr("alt");
                        $("#menuContainer").html('<img src="'+msg['now']+'" alt="'+alt+'" />');
                        window.location.hash = "menutop";

                        var I2 = new Image();
                        if(msg['next'] != 'none')
                            $(I2).attr("src", msg['next']);
                    });
                    $(I).attr("src", msg['now']);
                }
				else
	 				$("#menuLoading").slideUp();
           }
        });
    });

}


function loadMap(mapData)
{
    $.getScript("http://maps.google.com/maps/api/js?sensor=false&region=IN&callback=initMap");
}

function like() {
	
	var choice = this.id.toLowerCase();
	
	$.getJSON(HOST + "/php/liker.php", {"res_id" : RES_ID, "choice" : choice}, function (o, s){
		if (s) {
			window.notify(o.notices);
			if (o.success) {
				var counter = $('#like_count');
				var count = parseInt(counter.text());
				counter.text(count+o.likes);

				counter = $('#dislike_count');
				count = parseInt(counter.text());
				counter.text(count+o.dislikes);
			} 
		} else {
			window.notify([{msg: "Could not contact the servers. Please check your net connection.", lvl: "failure"}]);
		}
	});

	return false;
}

function addReviewEvents()
{
	$("#reviewSubmit").click(function(event){
		event.preventDefault();
		var review = escape($("#reviewTextBox").val());
		var rating = parseInt($("#userRating").val());
		var resId = RES_ID;

		if(review == "")
			$("#reviewMessage").html("Review cannot be blank!").slideDown().delay(5000).slideUp();
		else if(!(rating >= 1 && rating <= 5))
			$("#reviewMessage").html("Click on the stars below to rate the restaurant!").slideDown().delay(5000).slideUp();
		else
		{
			$("#reviewTextBox").val('Adding your review... please wait...').attr("disabled", "disabled");

			$.ajax({
				type: "POST",
				url: HOST+"php/submitReview.php",
				data: "review="+review+"&resId="+resId+"&rating="+rating,
				success: function(msg){
					if ($.browser.msie && $.browser.version.substr(0,1)<7) {
						$("#reviewMessage").html("Review added successfully!").slideDown().delay(5000).slideUp();
						$("#reviewTextBox").val('').removeAttr("disabled");
					} else {
						msg = eval('('+msg+')');
						if(msg.status == "success")
						{
							$("#reviewBox").prepend(msg.revHTML);

							$("#userRating").val("").parents(".ratingWidget").trigger('mouseout');
							$("#reviewMessage").html("Review added successfully!").slideDown().delay(5000).slideUp();
							$("#reviewTextBox").val('').removeAttr("disabled");
						}
						else
						{
							$("#reviewMessage").html("There was an error submitting your review. Please try again..").slideDown().delay(5000).slideUp();
							$("#reviewTextBox").val(review).removeAttr("disabled");
						}
					}
		   		}
			});
		}
	});
}


function initRatingWidget()
{
	$(".ratingWidget > div > a").tipsy({gravity: 'n'});
	$(".ratingWidget > div > a").mouseover(function(){
		var par = $(this).parent();
		var widget = par.parent();
		var pos = par.children().index(this);

		par.get(0).className = "stars2_"+((pos+1)*2);
	});

	$(".ratingWidget > div > a").click(function(event){
		event.preventDefault();
		$(this).parent().parent().find("input").val($(this).parent().children().index(this) + 1);
	});

	$(".ratingWidget").mouseout(function(){
		var val = $(this).find("input").val();
		if(!(val >= 1 && val <= 5)) val = 0;
		$(this).children("div").get(0).className = "stars2_"+(val*2);
	});
}

function photos_init(list)
{
	for(var i in list)
		$("#thumbsContainer").append('<a href="#"></a>')
	
	$("#thumbsContainer > a")
		.css("opacity", "0.5")
		.hover(
			function(){
				if(!$(this).hasClass("photo-showing"))
					$(this).animate({opacity: 1}, 500).css("border-color", "#333333");
			},
			function(){
				if(!$(this).hasClass("photo-showing"))
					$(this).animate({opacity: 0.5}, 500).css("border-color", "#dddddd");
			}
		);
	
	// Previous link
	$("#photoPrevious").click(function(){
		$("#thumbsContainer > a.photo-showing").prev().trigger("mouseover").trigger("click");
		return false;
	});

	// Next link
	$("#photoNext").click(function(){
		$("#thumbsContainer > a.photo-showing").next().trigger("mouseover").trigger("click");
		return false;
	});

	loadPhotos(list, 0);
	resizeImage();

	// tag the currently open thumb
	$("#thumbsContainer > a:first").addClass("photo-showing").css("opacity", 1);
}

function resizeImage()
{
	var img = $("#photoFrame > img");
	var imgx = img.width();
	var imgy = img.height();
	if(imgx > 650 && (650/imgx)*imgy < 1000)
		img.css("width", 650).css("height", (650/imgx)*imgy);
	else if(imgy > 1000)
		img.css("width", (1000/imgy)*imgx).css("height", 1000);
}

function loadPhotos(list, count)
{
	var pic = new Image();
	$(pic).load(function(){
		$("#thumbsContainer > a:eq("+count+")")
			.css("background-image", "url("+list[count]+")")
			.css("background-position", "50% 50%")
			.click(function(){
				if(!$(this).hasClass("photo-showing"))
				{
					$("#thumbsContainer > a.photo-showing").removeClass("photo-showing").trigger("mouseout");
					$(this).addClass("photo-showing");
					var idx = $("#thumbsContainer > a").index(this);
					$("#photoCounter").html(idx+1);
					$("#photoFrame > img").fadeOut(200, function(){
						$("#photoFrame").html('<img src="'+list[idx]+'" style="display: none;" />');
						resizeImage();
						$("#photoFrame > img").fadeIn(400);
					});
				}
				return false;
			});

		if(count < list.length - 1)
			loadPhotos(list, ++count);
	}).attr("src", list[count]);
}

function addClickToViewAction()
{
	$.ajax({
		type: "POST",
		url: HOST+"php/recordPhoneView.php",
		data: "res_id="+RES_ID,
		success: function(msg){
			window.CTV_id = msg;
		}
	});

	$("#clickToView").click(function(){
		clickToView_onclick();
		$("#clickToView").hide();
		$("#phoneNoString").show();

		return false;
	});
}

function clickToView_onclick()
{
	if(typeof(window.CTV_id) != 'undefined')
	{
		$.ajax({
			type: "POST",
			url: HOST+"php/recordPhoneView.php",
			data: "id="+window.CTV_id,
			success: function(msg){
			}
		});
	}
}
