var review_form_errors = '';
var ratings = new Array();
ratings[1] = 'Terrible';
ratings[2] = 'Poor';
ratings[3] = 'Average';
ratings[4] = 'Good';
ratings[5] = 'Excellent';
var hide_feedback = true;

$(function() {
	$("#accommodation").hide();
	$("#park").hide();
	$("#subjectprefix").hide();         		
	$(".question-mark").mouseenter(function()
	{
		if($(this).attr('id') == "" || $(this).attr('id') == "bush-vibe-explanation") {
			$(this).mousemove(function(e){
				$('#bushvibe-help').show();
				$('#bushvibe-help').css('left',e.pageX+5);
				$('#bushvibe-help').css('top',e.pageY+15);
				var direction = getDirection(($('#bushvibe-help').offset().top -$(window).scrollTop()));
				if(direction < 175) {
					$('#bushvibe-help').css('left',e.pageX);
					$('#bushvibe-help').css('top',e.pageY-164);
				}
			});
		} else {
			$(this).mousemove(function(e){
				$('#location-help').show();
				$('#location-help').css('left',e.pageX+5);
				$('#location-help').css('top',e.pageY+15);
				var direction = getDirection(($('#location-help').offset().top -$(window).scrollTop()));
				if(direction < 98) {
					$('#location-help').css('left',e.pageX);
					$('#location-help').css('top',e.pageY-88);
				}
			});
		}
	});
	$(".question-mark").mouseleave(function()
	{
		$('#bushvibe-help').hide();
		$('#location-help').hide();
	});
	
	$("#newsletteremail").blur(function()
	{
		doValidation('newsletter','blur');
	    $("#newsletteremail").keyup(function()
	    {
	      doValidation('newsletter','keyup');
	    });
	});
	$("#newsletterform").submit(function()
	{
	    doValidation('newsletter','submit');
	});
  
  	$("#contactemail").blur(function()
	{
	    doValidation('contact','blur');
	    $("#contactemail").keyup(function()
	    {
    		doValidation('contact','keyup');
    	});
  	});
  	$("#contactfeedback").blur(function()
	{
	  	doValidation('contact','blur');
    
  	});
  	$("#contactfeedback").keyup(function()
	{
	  doValidation('contact','keyup');
	});
	$("#contactform").submit(function()
	{
		doValidation('contact','submit');
	});
	
	if (!$("#country").is(':visible')) {
	   $("#country-label").hide();
	}
	if (!$("#park").is(':visible')) {
        $("#park-label").hide();
	}
	
	updateSelectedDropdowns();
	
	if ($("input[name=review_title]").length) {
	   if ($("input[name=review_title]").val() != '') {
	       // Redirect to empty form when clicked on back button
	       var randomnumber=Math.floor(Math.random()*9999);
	       document.location.href='/review/write/' + randomnumber;
	       return;
	   }
	}

    $(".formskip").each(function() {
        $(this).click(function() {
            $("input[name=skip]").val("true");
            window.onbeforeunload = null; 
            $("#writereview_form").submit();
            return false;
        });
    });
    
    $("#writereview_form").submit(function() {
    	$('#errors').remove();
    	if($("#reviewtype").val() != "accommodation" && $("#hash").val() != "") {
    		if($('form').get(0).getAttribute('action') == '/review/visited') {
    			$('form').get(0).setAttribute('action', '/review/additional');
    		}
	    }
        window.onbeforeunload = null; 
        //$('#errors').toggle();
        if (!validateReviewForm()) {
            window.scrollTo(0,$("#content").offset().top - 20);
            var error_intro = "<div class='error-title'><b>We're sorry!</b> We need you to correct or provide the following information:</div>";
            $("#writereview_form").before("<div id='errors' class='review_errors'>" + error_intro + review_form_errors + "</div>");
            
            $('.solved-text').toggle();
            $('.warning-solved').hide();
            window.onbeforeunload = unloadPage;
            return false;
        }
    });

    if ($("#reviewtype").val()) {
        window.onbeforeunload = unloadPage;
    }
    
    $("#reviewtype").change(function() {
    	if($("#reviewtype").val() == 'park') {
    		extractParkAndCountry();
    		setRatingTexts('park');
    	} else if($("#reviewtype").val() == 'country') {
    		setRatingTexts('country');
    	} else if($("#reviewtype").val() == 'accommodation') {
    		extractAccommodationParkAndCountry();
    		setRatingTexts('accommodation');
    	}
    });
    
    var ratings = new Array();
    ratings[1] = 'Terrible';
    ratings[2] = 'Poor';
    ratings[3] = 'Average';
    ratings[4] = 'Good';
    ratings[5] = 'Excellent';
   
    if($('#main-rating').length > 0) {
    	activateRating('main-rating', 'main-rating', 'big');
    	activateRating('main-rating-a', 'main-rating-a', 'small');
    	activateRating('main-rating-b', 'main-rating-b', 'small');
    	activateRating('main-rating-c', 'main-rating-c', 'small');
    	activateRating('main-rating-d', 'main-rating-d', 'small');
    }
    if($('#rating-country').length > 0) {
    	activateRating('rating-country', 'rating-country', 'big');
    	activateRating('rating-country-a', 'rating-country-a', 'small');
    	activateRating('rating-country-b', 'rating-country-b', 'small');
    	activateRating('rating-country-c', 'rating-country-c', 'small');
    	activateRating('rating-country-d', 'rating-country-d', 'small');
    }
    if($('#rating-park').length > 0) {
    	activateRating('rating-park', 'rating-park', 'big');
    	activateRating('rating-park-a', 'rating-park-a', 'small');
    	activateRating('rating-park-b', 'rating-park-b', 'small');
    	activateRating('rating-park-c', 'rating-park-c', 'small');
    	activateRating('rating-park-d', 'rating-park-d', 'small');
    }
    if($('#rating-operator').length > 0) {
    	activateRating('rating-operator', 'rating-operator', 'big');
    }
    
    if ($("#feedback").length) {
    	if($("#month").length > 0) {
    		
    		if (!$.cookie('feedbackpopup')) {
    			$("#feedback").delay(15000).animate({
                    bottom: '0'
                }, 'fast', function() {
                	$.cookie('feedbackpopup', 1, { expires: 365 });
                	setTimeout("hideFeedback()", 4000);
                });
            } else {
                $("#feedback").find('.minmax').html('+  ');
                $("#feedback").find('.minmax').css('font-size', '14px');
                $("#feedback").find('.minmax').css('line-height', '17px');
                $("#feedback").css('bottom', '-155px');
            }
    		
		} else {
			hideFeedback();
		}
        

        $("#feedback").find('textarea').focus(function() {
            hide_feedback = false;
        });
        $("#feedback").find('a').click(function() {
            if ($(this).html() == '-') {
                $("#feedback").animate({
                    bottom: '-155px'
                }, 'fast',  function() {
                    $("#feedback").find('.minmax').html('+');
                    $("#feedback").find('.minmax').css('font-size', '14px');
                    $("#feedback").find('.minmax').css('line-height', '17px');
                });
            } else {
                $("#feedback").animate({
                    bottom: '0px'
                }, 'fast', function() {
                    $("#feedback").find('.minmax').html('-');
                    $("#feedback").find('.minmax').css('font-size', '20px');
                    $("#feedback").find('.minmax').css('line-height', '14px');
                });
            }
        });
        
        $("#feedbackform").submit(function() {
            if ($('#feedbacktext').length) {
                var OSName="Unknown OS";
                if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
                if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
                if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
                if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
                $.post('/review/handlefeedback',
                {
                    "feedbacktext": $('#feedbacktext').val(),
                    "uid": $('#uid').val(),
                    "feedbackpage": $("#feedbackpage").val(),
                    "url": window.location.href,
                    "browser": detectBrowserVersion(),
                    "os": OSName,
                    "screen": screen.width + "x" + screen.height,
                    "window": $(window).width() + "x" + $(window).height()
                },
                function(data) {
                    $("#feedbackform > p").html('<b>Thank you!</b><br />If you\'d like feedback on this issue, please enter your name and email.');
                    $("#feedbacktext").replaceWith('<input type="text" id="feedbackname" value="Enter your name" onfocus="if ($(this).val() == \'Enter your name\') { $(this).val(\'\');$(this).css(\'color\', \'#444444\'); }" onblur="if ($(this).val() == \'\') { $(this).val(\'Enter your name\');$(this).css(\'color\', \'#abadb3\'); }" /><br /><input type="text" id="feedbackemail" value="Enter email address" onfocus="if ($(this).val() == \'Enter email address\') { $(this).val(\'\');$(this).css(\'color\', \'#444444\'); }" onblur="if ($(this).val() == \'\') { $(this).val(\'Enter email address\');$(this).css(\'color\', \'#abadb3\'); }" />');
                    $("#feedbacksubmitbutton").removeClass('hover');
                    $("#feedbacksubmitbutton").addClass('normal');
                }, 'json');
                return false;
            } else if ($("#feedbackname").length) {
                $.post('/review/handlefeedback',
                {
                    "feedbackname": $('#feedbackname').val(),
                    "feedbackemail": $('#feedbackemail').val(),
                    "uid": $('#uid').val()
                },
                function(data) {
                    $("#feedbackform > p").html('<b>Thank you!<br /><br />We will contact you as soon as possible.</b>');
                    $("#feedbackname").remove();
                    $("#feedbackemail").remove();
                    $("#feedbacksubmitbutton").remove();
                    $("#feedback").delay(3000).animate({
                        bottom: '-200px'
                    }, 'fast');
                }, 'json');
                return false;            
            }
        });
    }
    
    if($("#reviewtype").val() == "park"){
    	getParksCheckboxes($("input[name=pa_country]").val(), $("input[name=park]").val());
    	extractParkAndCountry();
    	setRatingTexts('park');
    } else if($("#reviewtype").val() == "country") {
    	$("#otherparks_pretitle").html('Which parks did you visit');
    	setRatingTexts('country');
	} else if($("#reviewtype").val() == "accommodation") {
		$("#otherparks_pretitle").html('Which parks did you visit');
		extractAccommodationParkAndCountry();
		setRatingTexts('accommodation');
	}
    
    if($("#operator_name").length > 0) {
	    $("#operator_name").blur(function() {
	    	extractOperator();
	    });
	    $("#operator_name").autocomplete({
			source: "/data/operatorsac/",
			minLength: 1,
			delay: 0
		}).data("autocomplete")._renderItem = function( ul, item ) {
	       return $( "<li></li>" )
	       .data( "item.autocomplete", item )
	       .append( "<a>"+ item.label + "</a>" )
	       .appendTo( ul );
	    };
	    $(".ui-autocomplete").click(function() {
	    	extractOperator();
	    });
	}
    
    $("#review").blur(function(){
    	if($("#review").val().length < 50) {
    		$("#note2").css("color","#bf1311");
    	}
    });
    $("#review").keyup(function(){
    	if($("#review").val().length >= 50) {
    		$("#note2").css("color","#666666");
    	}
    });
    
});

function hideFeedback() {
    if (hide_feedback == false) {
        return;
    }
    $("#feedback").animate({
        bottom: '-155px'
    }, 'fast',  function() {
        $("#feedback").find('a').html('+');
        $("#feedback").find('a').css('font-size', '14px');
    });
}

function detectBrowserVersion(){
    var userAgent = navigator.userAgent.toLowerCase();
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    var version = 0;
    
    // Is this a version of IE?
    if($.browser.msie){
    userAgent = $.browser.version;
    version = "Internet Explorer " + userAgent;
    }
    
    // Is this a version of Chrome?
    if($.browser.chrome){
    userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
    version = "Chrome " + userAgent;
    // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
    $.browser.safari = false;
    }
    
    // Is this a version of Safari?
    if($.browser.safari){
    userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);	
    version = "Safari " + userAgent;	
    }
    
    // Is this a version of Mozilla?
    if($.browser.mozilla){
    //Is it Firefox?
    if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
    userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
    version = "Mozilla Firefox " + userAgent;
    }
    // If not then it must be another Mozilla
    else{
    userAgent = userAgent;
    version = "Mozilla " + userAgent;
    }
    }
    
    // Is this a version of Opera?
    if($.browser.opera){
    userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
    version = "Opera " + userAgent;
    }
    return version;
}

function activateRating(id, name, size) {
    $('#' + id).raty({
        size:       24,
        scoreName:  name,
        starOff:    'star-off-'+size+'.png',
        starOn:     'star-on-'+size+'.png',
        path:       '/images/',
        hintList:     ['Terrible', 'Poor', 'Average', 'Good', 'Excellent'],
        mouseenter: function(score) {
            $('#' + id + '-label').html(ratings[score]);
            $('#' + id + '-label').removeClass('stars-label-yellow');
            $('#' + id + '-label').addClass('stars-label-grey');
        },
        mouseleave: function(score) {
            if (score == 0) {
                $('#' + id + '-label').html('Select stars');
                $('#' + id + '-label').removeClass('stars-label-grey');
                $('#' + id + '-label').addClass('stars-label-yellow');
            } else {
                $('#' + id + '-label').html(ratings[score]);
                $('#' + id + '-label').removeClass('stars-label-grey');
                $('#' + id + '-label').addClass('stars-label-grey');
            }
        }
        
    });     
}

function animateThis(id) {
    $('#other-park-review-' +id).toggle('slow');
}

function checkedParks() {
    var checked_parks = $(".other_parks:checked").length;
    $('.other_parks').each(function () {
        var id = $(this).attr('id').replace(/visited_park_/, '');
    });

    if (checked_parks > 0) {
        if (checked_parks == 1) {
            $("#ask_parks_reviews_title").html('Would you like to review this park?');
        } else {
            $("#ask_parks_reviews_title").html('Would you like to review these parks?');
        }
//        $("#ask_parks_reviews").show();
        showExtraReviewFields();
    } else {
  //      $("#ask_parks_reviews").hide();
    }
}

function showExtraReviewFields() {
	var checked_parks = $(".other_parks:checked").length;
	var html = '';
	var this_block = '';
    var left_block = '';
    var right_block = '';
	var toActivate = new Array();
    $('.other_parks').each(function () {
        this_block = '';
        var id = $(this).attr('id').replace(/visited_park_/, '');

        this_block += "<div id=\"other-park-review-" + id + "\" style=\"display:none;\">";

        this_block += "<h3 id=\"title-extra_review_rating-"+id+"\"><b>How would you rate</b> <span id=\"park_name_for_error-" + id + "\">" + $(this).next('label').text() + "</span> as a safari destination? <span class=\"optional\">(optional)</span></h3>";
        this_block += "<div id=\"warning-extra_review_rating-"+id+"\" class=\"warning\"></div><div id=\"warning-extra_review_rating-"+id+"-solved\" class=\"warning-solved\" style=\"display: none;\">Solved</div>";
        this_block += "<div class=\"form-indent\"><div class=\"rating-block\">";
        this_block += "<div class=\"overall\">Overall rating</div> <div class=\"float-left\"><span id=\"rating-" + id + "\" class=\"stars clickstars\"></span> <span class=\"rating_exp\"> <span id=\"rating-" + id + "-label\" class=\"stars-label-yellow\">Select stars</span></span></div>";
        this_block += "<div class=\"clear\"></div>";
        this_block += "<div class=\"rating-block-small\">";
        this_block += "<div class=\"line\">&rsaquo; Wildlife</div> <div class=\"float-left\"><span id=\"rating-" + id + "-a\" class=\"stars clickstars\"></span></div><div class=\"float-left\"><input id=\"rating-" + id + "-a-check\" type=\"checkbox\" onclick=\"checkNotSure('rating-" + id + "-a', 'on');\" /></div> <div class=\"notsure\"><label for=\"rating-" + id + "-a-check\">Not sure</label></div>";
        this_block += "<div class=\"line\">&rsaquo; Scenic beauty</div> <div class=\"float-left\"><span id=\"rating-" + id + "-b\" class=\"stars clickstars\"></span></div><div class=\"float-left\"><input id=\"rating-" + id + "-b-check\" type=\"checkbox\" onclick=\"checkNotSure('rating-" + id + "-b', 'on');\" /></div> <div class=\"notsure\"><label for=\"rating-" + id + "-b-check\">Not sure</label></div>";
        this_block += "<div class=\"line\">&rsaquo; Bush vibe <img src=\"/images/question-mark.png\" class=\"question-mark\"></div> <div class=\"float-left\"><span id=\"rating-" + id + "-c\" class=\"stars clickstars\"></span></div><div class=\"float-left\"><input id=\"rating-" + id + "-c-check\" type=\"checkbox\" onclick=\"checkNotSure('rating-" + id + "-c', 'on');\" /></div> <div class=\"notsure\"><label for=\"rating-" + id + "-c-check\">Not sure</label></div>";
        this_block += "<div class=\"line\">&rsaquo; Birding</div> <div class=\"float-left\"><span id=\"rating-" + id + "-d\" class=\"stars clickstars\"></span></div><div class=\"float-left\"><input id=\"rating-" + id + "-d-check\" type=\"checkbox\" onclick=\"checkNotSure('rating-" + id + "-d', 'on');\" /></div> <div class=\"notsure\"><label for=\"rating-" + id + "-d-check\">Not sure</label></div>";
        this_block += "</div>";
        this_block += "<div class=\"clear\"></div>";
        this_block += "<div id=\"warning-extra_review-"+id+"\" class=\"warning\" style=\"margin-left: 0px;\"></div><div id=\"warning-extra_review-"+id+"-solved\" class=\"warning-solved\" style=\"display: none; margin-left: 0px;\">Solved</div>";
        this_block += "<div class=\"extra_review_description\">Briefly explain why</span></div>";
        this_block += "<textarea id=\"extrareview-"+id+"\" name=\"extrareview[" + id +"]\" onkeyup=\"if($(this).val().length > 0) { solveUnsolve('extra_review-"+id+"','solve'); } else { solveUnsolve('extra_review-"+id+"','unsolve'); }\"></textarea>";
        
        this_block += "</div></div>";
        toActivate.push(id);
        
        this_block += "</div>";
        
        if ($(this).hasClass('right')) {
            right_block += this_block;
        } else {
            left_block += this_block;            
        }
    });
    
    html = left_block + right_block;
    
    if ($("#other_parks_reviews").html() == '') {
    	$("#other_parks_reviews").html(html);
        for(i=0; i<toActivate.length; i++) { 
            activateRating('rating-' + toActivate[i], "extrarating[" + toActivate[i] + "]", 'big');
            activateRating('rating-' + toActivate[i] + '-a', "extrarating_a[" + toActivate[i] + "]", 'small');
            activateRating('rating-' + toActivate[i] + '-b', "extrarating_b[" + toActivate[i] + "]", 'small');
            activateRating('rating-' + toActivate[i] + '-c', "extrarating_c[" + toActivate[i] + "]", 'small');
            activateRating('rating-' + toActivate[i] + '-d', "extrarating_d[" + toActivate[i] + "]", 'small');
        }
        $(".question-mark").mouseenter(function()
		{
        	$(".question-mark").mousemove(function(e){
    			
    			$('#bushvibe-help').show();
    			$('#bushvibe-help').css('left',e.pageX+5);
    			$('#bushvibe-help').css('top',e.pageY+15);
    			var direction = getDirection(($('#bushvibe-help').offset().top -$(window).scrollTop()));
    			if(direction < 175) {
    				$('#bushvibe-help').css('left',e.pageX);
    				$('#bushvibe-help').css('top',e.pageY-165);
    			}
    		});
		});
		$(".question-mark").mouseleave(function()
		{
			$('#bushvibe-help').hide();
		});
    }
}

function markAsRequired(id) {
    $("#" + id).addClass('error-required');
}

function unloadPage(){
    return "Are you sure you want to leave this page?\nYour review will be lost.";
}

function solveUnsolve(section, action, text) {
	if($("#errors-"+section).length != 0) {
		
		var title = '';
		
		if($.browser.msie && $.browser.version < 9.0) {
			var first = 10;
			var second = 30;
		} else {
			var first = 300;
			var second = 1000;
		}
		
		if(section == 'rating-country-review') {
			title = 'rating-country';
		} else if(section.search('extra_review-') != -1) {
			title = section.replace('extra_review-','extra_review_rating-');
		} else {
			title = section;
		}
		
		if(action == 'solve') {
			if(!$("#errors-"+section).hasClass("solved")) {
				$("#errors-"+section).toggleClass("solved");
				$("#solved-"+section).fadeIn(1500);
				$("#title-"+title).css("color","#444444");
				$("#warning-"+section).fadeOut(first, function() { $("#warning-"+section+"-solved").fadeIn(second, function() { $("#warning-"+section).hide(); }); });
			}
		} else {
			if($("#errors-"+section).hasClass("solved")) {
				$("#errors-"+section).toggleClass("solved");
				$("#solved-"+section).fadeOut(500);
				$("#title-"+title).css("color","#cb261c");
				$("#warning-"+section+"-solved").fadeOut(first, function() { $("#warning-"+section).fadeIn(second, function() { $("#warning-"+section+"-solved").hide(); }); });
			}
		}
	}	
	if(section == 'about') {
		solveUnsolve('country',action);
		solveUnsolve('park',action);
		solveUnsolve('operator',action);
	}
	
}

function validateReviewForm() {
	if ($("input[name=skip]").val() == "true") {
        return true;
    }

    review_form_errors = '';

    $("*").removeClass("error-required");
    $("*").removeClass("field-error");
    
    var success = true;
    
    if($('#reward_radios').length > 0) {
	    if ($("input[name='reward_radio']:checked").val() == undefined) {
	    	markAsRequired('title-reward');
	        review_form_errors += "<span id='errors-reward'>- Please select your reward</span><span id=\"solved-reward\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-reward').html("Please select your reward");
	        success = false;
	    } else if($("input[name='reward_radio']:checked").val() == '1' && $("#re1").val().length < 6) {
	    	markAsRequired('title-reward');
	        review_form_errors += "<span id='errors-reward'>- Please enter your email address for your reward</span><span id=\"solved-reward\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-reward').html("Please enter your email address for your reward");
	        $('#re1').addClass('field-error');
	    } else if($("input[name='reward_radio']:checked").val() == '2' && $("#re2").val().length < 6) {
	    	markAsRequired('title-reward');
	        review_form_errors += "<span id='errors-reward'>- Please enter your email address for your reward</span><span id=\"solved-reward\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-reward').html("Please enter your email address for your reward");
	        $('#re2').addClass('field-error');
	    }
    }
    
    if ($('#reviewtype').length > 0) {
    	if ($('#reviewtype').val() == '-' ||
    			$('#reviewtype').val() == 'country' && $('#country').val() == '-' ||
    			$('#reviewtype').val() == 'park' && ($('#park').val() == '' || $('#park').val() == 'Enter the name of the park') ||
    			$('#reviewtype').val() == 'accommodation' && ($('#accommodation').val() == '' || $('#accommodation').val() == 'Enter the name of the accommodation') ||
    			$('#reviewtype').val() == 'operator' && $('#operator').val() == '-' ||
    			$('#reviewtype').val() == 'operator' && $('#operator').val() == '-1' && ($('#alternative-operator-name').val() == '' || $('#alternative-operator-name').val() == 'Enter the name of the operator here')) {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-about'>- Please select what your review is about</span><span id=\"solved-about\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-about').html("Please select what your review is about");
	        $('#reviewtype').addClass('field-error');
	        success = false;    
	    }
	    /*if ($('#reviewtype').val() == 'country' && $('#country').val() == '-') {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-country'>- Please select the country your review is about</span><span id=\"solved-country\" class=\"solved-text\">Solved</span><br />";
	        $('#country').addClass('field-error');
	        success = false;
	    }
	    if ($('#reviewtype').val() == 'park' && ($('#park').val() == '' || $('#park').val() == 'Enter the name of the park')) {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-park'>- Please enter the park your review is about</span><span id=\"solved-park\" class=\"solved-text\">Solved</span><br />";
	        $('#park').addClass('field-error');
	        success = false;    
	    }
	    if ($('#reviewtype').val() == 'accommodation' && ($('#accommodation').val() == '' || $('#accommodation').val() == 'Enter the name of the accommodation')) {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-accommodation'>- Please enter the accommodation your review is about</span><span id=\"solved-park\" class=\"solved-text\">Solved</span><br />";
	        $('#accommodation').addClass('field-error');
	        success = false;    
	    }
	    if ($('#reviewtype').val() == 'operator' && $('#operator').val() == '-') {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-operator'>- Please select the operator your review is about</span><span id=\"solved-operator\" class=\"solved-text\">Solved</span><br />";
	        $('#operator').addClass('field-error');
	        success = false;    
	    }
	    if ($('#reviewtype').val() == 'operator' && $('#operator').val() == '-1' && ($('#alternative-operator-name').val() == '' || $('#alternative-operator-name').val() == 'Enter the name of the operator here')) {
	        markAsRequired('title-about');
	        review_form_errors += "<span id='errors-otheroperator'>- Please enter the name of the other operator</span><br />";
	        success = false;    
	    }*/
	    
	    if ($('#month').val() <= 0 || $('#year').val() <= 0) {
	        markAsRequired('title-monthyear');
	        review_form_errors += "<span id='errors-monthyear'>- Please select the month and year of your visit</span><span id=\"solved-monthyear\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-monthyear').html("Please select the month and year of your visit");
	        if($('#month').val() <= 0) { $('#month').addClass('field-error'); }
	        if($('#year').val() <= 0) { $('#year').addClass('field-error'); }
	        success = false;
	    } else {
	        if ($('#year').val() == (new Date).getFullYear() && $('#month').val() > ((new Date).getMonth() + 1)) {
	            markAsRequired('title-monthyear');
    	        $('#warning-monthyear').html("Please select a month and year in the past");
	            $('#month').addClass('field-error');
	            $('#year').addClass('field-error');
	            review_form_errors += "<span id='errors-monthyear'>- Please select a month and year in the past</span><span id=\"solved-monthyear\" class=\"solved-text\">Solved</span><br />";
	            success = false;
	        }
	    }
	    
	    if ($('input:hidden[name=main-rating]').val() < 1 || $('input:hidden[name=main-rating]').val() > 5) {
	        markAsRequired('title-main-rating');
	        review_form_errors += "<span id='errors-main-rating'>- Please add a rating to your review</span><span id=\"solved-main-rating\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-main-rating').html("Please add a rating to your review");
	        success = false;
	    }
	    
	    if ($('#review_title').val().length < 2) {
	        markAsRequired('title-title');
	        markAsRequired('review_title-label label');
	        review_form_errors += "<span id='errors-title'>- Please enter a title for your review</span><span id=\"solved-title\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-title').html("Please enter a title for your review");
	        $('#review_title').addClass('field-error');
	        success = false;    
	    }
	    
	    if($('#review').length != 0) {
	    	if ($('#review').val().length < 50) {
		        markAsRequired('title-review');
		        review_form_errors += "<span id='errors-review'>- Please write a review with a minimum of 50 characters</span><span id=\"solved-review\" class=\"solved-text\">Solved</span><br />";
		        $('#warning-review').html("Please write a review with a minimum of 50 characters");
		        $('#review').addClass('field-error');
		        success = false;
	    	}
	    }
	    if($('#review_250').length != 0) {
	    	if ($('#review_250').val().length < 250) {
		        markAsRequired('title-review');
		        review_form_errors += "<span id='errors-review'>- Please write a review with a minimum of 250 characters</span><span id=\"solved-review\" class=\"solved-text\">Solved</span><br />";
		        $('#warning-review').html("Please write a review with a minimum of 250 characters");
		        $('#review_250').addClass('field-error');
		        success = false;
	    	}
	    }
	
	    // Check if extra reviews are filled in
	    if($("input[name='review_other_parks']:checked").val() == 1) {
	    	 var rating_forgotten = false;
	    	 $("input:checkbox[name='visited_parks[]']:checked").each(function()
			 {
			     // add $(this).val() to your array
	    		 if(typeof($("input[name='extrarating["+$(this).val()+"]']:checked").val()) == 'undefined') {
	    			 rating_forgotten = true;
	    			 review_form_errors += "<span id='errors-reviewpark'>- Please enter a review for "+$('#park_name_for_error-'+$(this).val()).html()+"</span><br />";
	    			 markAsRequired('extra_review_'+$(this).val());
	    		 }
			 });
	    	 if(rating_forgotten == true) {
	    		 markAsRequired('ask_parks_reviews_title');
	    		 success = false;
	    	 }
	    }
	    
	    if ($('#reviewer_name').val().length < 2) {
	        markAsRequired('title-reviewername');
	        markAsRequired('reviewer_name-label label');
	        review_form_errors += "<span id='errors-reviewername'>- Please enter your name</span><span id=\"solved-reviewername\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-reviewername').html("Please enter your name");
	        $('#reviewer_name').addClass('field-error');
	        success = false;    
	    }
    }
    
	if($("#review_country_div").length != 0) {
    	if($('#review_country').val() != "") {
    		if($('input:hidden[name="rating-country"]').val() == 0) {
	    		markAsRequired('title-rating-country');
	    		country_name = $('input:hidden[name=country_name]').val();
	    		if(country_name == undefined) {
	    			country_name = $("#country option:selected").text();
	    		}
	    		review_form_errors += "<span id='errors-rating-country'>- Please choose a rating for "+country_name+"</span><span id=\"solved-rating-country\" class=\"solved-text\">Solved</span><br />";
	    		$('#warning-rating-country').html("Please choose a rating for "+country_name);
		        success = false;
    		}
    	} else {
    		if($('input:hidden[name="rating-country"]').val() > 0) {
	    		markAsRequired('title-rating-country');
	    		country_name = $('input:hidden[name=country_name]').val();
	    		if(country_name == undefined) {
	    			country_name = $("#country option:selected").text();
	    		}
	    		review_form_errors += "<span id='errors-rating-country-review'>- Please briefly explain your rating for "+country_name+"</span><span id=\"solved-rating-country-review\" class=\"solved-text\">Solved</span><br />";
	    		$('#warning-rating-country-review').html("Please briefly explain your rating for "+country_name);
		        success = false;
    		}
    	}
    }
    
    if($("#contact_no").length != 0) {
    	if($("input[name='reviewer_contact']:checked").val() == "yes" && $("#reviewer_email").val().length < 6) {
    		markAsRequired('title-allow');
	        review_form_errors += "<span id='errors-allow'>- Please enter your email address if you want others to be able to email you</span><span id=\"solved-allow\" class=\"solved-text\">Solved</span><br />";
	        $('#warning-allow').html("Please enter your email address");
	        $('#reviewer_email').addClass('field-error');
    		success = false;
    	}
    }
    
    if($(".other_parks:checked").length != 0) {
    	$.each($(".other_parks:checked"), function() {
	    	if($("#extrareview-"+$(this).val()).val() != "" && $('input[name="extrarating['+$(this).val()+']"]').val() == 0) {
	    		review_form_errors += "<span id='errors-extra_review_rating-"+$(this).val()+"'>- Please choose a rating for "+$(this).next().text()+"</span><span id=\"solved-extra_review_rating-"+$(this).val()+"\" class=\"solved-text\">Solved</span><br />";
	    		$('#warning-extra_review_rating-'+$(this).val()).html("Please choose a rating for "+$(this).next().text());
	    		markAsRequired('title-extra_review_rating-'+$(this).val());
		        success = false;
	    	}
	    	if($("#extrareview-"+$(this).val()).val() == "" && $('input[name="extrarating['+$(this).val()+']"]').val() > 0) {
	    		review_form_errors += "<span id='errors-extra_review-"+$(this).val()+"'>- Please briefly explain your rating for "+$(this).next().text()+"</span><span id=\"solved-extra_review-"+$(this).val()+"\" class=\"solved-text\">Solved</span><br />";
	    		$('#warning-extra_review-'+$(this).val()).html("Please briefly explain your rating for "+$(this).next().text());
	    		markAsRequired('title-extra_review_rating-'+$(this).val());
		        success = false;
	    	}
		});
    }
    
    return success;
}

function validateDate() {
    if(!$("#errors-monthyear").length) {
        return;    
    }
    var error = false;
    if ($('#year').val() == (new Date).getFullYear() && $('#month').val() > ((new Date).getMonth() + 1)) {
        // Future
        $('#month').addClass("field-error");
        $('#year').addClass("field-error");
        $('#warning-monthyear').html("Please select a month and year in the past");
        error = true;
    } else {
        // Past
        if ($('#month').val() != 0) {
            $('#month').removeClass("field-error");            
        } else {
            $('#month').addClass("field-error");   
            error = true;                 
        }
        if ($('#year').val() != 0) {
            $('#year').removeClass("field-error");            
        } else {
            $('#year').addClass("field-error");     
            error = true;               
        }
        if (error == true) {
	        $('#warning-monthyear').html("Please select the month and year of your visit");
        }
    }
    
    if (error == true) {
        solveUnsolve("monthyear","unsolve");
    } else {
        solveUnsolve("monthyear","solve");
    }
}

function updateSelectedDropdowns(changecountry) {
	if (!$("#reviewtype").length) {
        return;
    }
		
	$("#accommodation").hide();
	$("#park").hide();
    $("#country-label").hide();
    $("#country").hide();    
    $("#park-label").hide();
    $("#park").hide();    
    $("#operator-label").hide();
    $("#operator").hide();  
    $("#alternative-park-name").hide();  

    if ($("#reviewtype").val() == 'country') {
        $("#photoscontainer").show();
        $("#country-label").show();
        $("#country").show();

        if ($("#country").val() == '-') {
        	$('#selection-ok-button').hide();
            $("#parkscontainer").hide();
        } else {
        	if($("#hash").val() != "") {
            	$("#parkscontainer").show();
        	}
            $('#selection-ok-button').show();
        }
        $("#changelink").html('Change country?');

    } else if ($("#reviewtype").val() == 'park') {
    	$("#photoscontainer").show();
        $("#country-label").show();
        $("#park-label").show();
        if($("#park").val() == "") {
		    $("#park").val('Enter the name of the park');
			$("#park").addClass('lightgrey');
        }
        
        if ($("#park").val() != '' && $("#park").val() != 'Enter the name of the park') {
        	$('#selection-ok-button').show();
            $("#parkscontainer").show();
        } else {
            $('#selection-ok-button').hide();
            $("#parkscontainer").hide();
        }
        
        $("#park").show();
        $("#park").autocomplete({
    		source: "/data/parksac/",
    		minLength: 1,
    		delay: 0
    	}).data("autocomplete")._renderItem = function( ul, item ) {
	       return $( "<li></li>" )
           .data( "item.autocomplete", item )
           .append( "<a>"+ item.label + "</a>" )
           .appendTo( ul );
        };
        $("#park").keyup(function() {
    		if($("#park").val() != "") {
    			$('#selection-ok-button').show();
    		} else {
    			$('#selection-ok-button').hide();
    		}
    		changeTitles();
    	});
        $("#park").focus(function() {
        	if($("#park").val() == "Enter the name of the park") {
        		$("#park").val('');
        		$("#park").removeClass('lightgrey');
        	}
    	});
        $("#park").blur(function() {
        	if($("#park").val() == "") {
        		$("#park").val('Enter the name of the park');
        		$("#park").addClass('lightgrey');
        		$("#subjectprefix").hide();
        	}
        	
        	extractParkAndCountry();
			changeTitles();
        });
        $(".ui-autocomplete").click(function() {
        	extractParkAndCountry();
        	changeTitles();
        });
        
        $("#changelink").html('Change park?');
    } else if ($("#reviewtype").val() == 'accommodation') {
    	$("#photoscontainer").show();
    	$("#accommodation").show();
    	$("#parkscontainer").hide();
    	if($("#accommodation").val() == "") {
    		$("#accommodation").val('Enter the name of the accommodation');
    		$("#accommodation").addClass('lightgrey');
    	}

    	if ($("#accommodation").val() != '' && $("#accommodation").val() != 'Enter the name of the accommodation') {
        	$('#selection-ok-button').show();
        } else {
            $('#selection-ok-button').hide();
        }
    	
        $("#accommodation").show();
        $("#accommodation").autocomplete({
    		source: "/data/accommodationsac/",
    		minLength: 1,
    		delay: 0
    	}).data("autocomplete")._renderItem = function( ul, item ) {
    	       return $( "<li></li>" )
               .data( "item.autocomplete", item )
               .append( "<a>"+ item.label + "</a>" )
               .appendTo( ul );
           };
        $("#accommodation").keyup(function() {
    		if($("#accommodation").val() != "" && $("#accommodation").val() != 'Enter the name of the accommodation') {
    			$('#selection-ok-button').show();
    			$("#accommodation").removeClass('lightgrey');
    		} else {
    			$('#selection-ok-button').hide();
    			$("#accommodation").addClass('lightgrey');
    		}
    		changeTitles();
    	});
        $("#accommodation").focus(function() {
        	if($("#accommodation").val() == "Enter the name of the accommodation") {
        		$("#accommodation").val('');
        		$("#accommodation").removeClass('lightgrey');
        	}
    	});
        $("#accommodation").blur(function() {
        	if($("#accommodation").val() == "") {
        		$("#accommodation").val('Enter the name of the accommodation');
        		$("#accommodation").addClass('lightgrey');
        		$("#subjectprefix").hide();
        	}
        	extractAccommodationParkAndCountry();
        	changeTitles();
        });
        $(".ui-autocomplete").click(function() {
        	extractAccommodationParkAndCountry();
        	changeTitles();
        });
        
        $("#changelink").html('Change accommodation?');
    } else if ($("#reviewtype").val() == 'operator') {
        $("#photoscontainer").hide();
        $("#operator-label").show();
        $("#operator").show();
        $("#parkscontainer").hide();
        
        $("#changelink").html('Change operator?');
    } else {
    	$('#selection-ok-button').hide();
    }
    
    changeTitles();
}

function getParksDropdown(countryid, selected) {
	
	$.getJSON("/data/parksbycountryid/id/" + countryid, function(data) {
    
        auxArr1 = [];
        auxArr1[0] = "<option value='-'>- select a park -</option>";
        
        if (selected == -1) {
            auxArr1[1] = "<option value='-1' selected>- other park -</option>";
        } else {
            auxArr1[1] = "<option value='-1'>- other park -</option>";
        }
        
        $.each(data, function(i,item){
            if (selected == item.park_id) {
                auxArr1[i + 2] = "<option value='" + item.park_id + "' selected>" + item.name + "</option>";
            } else {
                auxArr1[i + 2] = "<option value='" + item.park_id + "'>" + item.name + "</option>";
            }
        });

        

        $('#park').html(auxArr1.join(''));
    });
}

function sortObj(arr){
    // Setup Arrays
    var sortedKeys = new Array();
    var sortedObj = {};
 
    // Separate keys and sort them
    for (var i in arr){
        sortedKeys.push(i);
    }
    sortedKeys.sort();
 
    // Reconstruct sorted obj based on keys
    for (var i in sortedKeys){
        sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
    }
    return sortedObj;
}

function getParksCheckboxes(countryid, hide_park_id) {
	
	if(countryid == null)
		return;
	
    $.getJSON("/data/parksbycountryid/id/" + countryid, function(data) {
    
    	auxArr = [];
        
    	var float = "";
    	var side = "left";
        if(data.length > 6) {
        	 float = " class=\"float\"";
        }
        var j = 0;
        var k = -2;
        $.each(data, function(i,item){
            if (item.park_id != hide_park_id) {
                if (data.length > 6) {
                	if (j >= Math.ceil(data.length / 2)) {
                	   if (k % 2 == 0) {
                	       k = -1;
                	   }
                	   k = k +2;
                	} else {
                	   k = k +2;                	   
                	}
                	if (k % 2 == 0) {
                        side = "left";
                	} else {
                        side = "right";
                	}
                	auxArr[k] = "<li"+float+"><input type=\"checkbox\" name=\"visited_parks[]\" class=\"other_parks "+side+"\" onclick=\"checkedParks(); animateThis("+item.park_id+");\" id=\"visited_park_"+item.park_id+"\" value=\""+item.park_id+"\"/> <label for=\"visited_park_"+item.park_id+"\">" + item.name + "</label></li>";                    
                    j++;
                } else {
                	auxArr[i] = "<li"+float+"><input type=\"checkbox\" name=\"visited_parks[]\" class=\"other_parks "+side+"\" onclick=\"checkedParks(); animateThis("+item.park_id+");\" id=\"visited_park_"+item.park_id+"\" value=\""+item.park_id+"\"/> <label for=\"visited_park_"+item.park_id+"\">" + item.name + "</label></li>";
                }
            }
        });
        
        $('#otherparks-div').html('<ul id="otherparks">' + auxArr.join('') + '</ul><div class="clear"></div>');
        $('#other_parks_reviews').html('');
    });
    
}

function changeTitles(changeparks) {
	if($("#country").is(":visible") && $("#country").val() != '-') {
		getParksCheckboxes($("#country").val(), $("#park").val());
	}
	
	if($("#reviewtype").val() == 'country' && $("#country").val() != '-') {
		$("#subject").html($("#country option:selected").text());
		if($("#review_country_container").is(":visible")) {
			$("#review_country_container").toggle('normal');
		}
		if($("#review_park_container").is(":visible")) {
			$("#review_park_container").toggle('normal');
		}
		$("#subject-describe").html($("#country option:selected").text());
		$("#thinkabout").html('wildlife, scenery, weather, accommodations, food, transportation, your guide, other highlights');
		$("#rate-title").html('<span class="font-weight-normal">'+$("#country option:selected").text() + ' as a safari destination?</span>');
		$("#review-title").html(' about ' + $("#country option:selected").text());
		$("#when-title").html('<span class="font-weight-normal">go to ' + $("#country option:selected").text()+'?');
		$("#review_title-title").html(' about ' + $("#country option:selected").text());
		$("#otherparks_pretitle").html('Which parks did you visit');
		$("#otherparks-title").html('');		
        $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
	} else if($("#reviewtype").val() == 'park') {
		if($("#review_park_container").is(":visible") && window.location.pathname.indexOf('visited') == -1) {
			$("#review_park_container").toggle('normal');
		}
		if($("#park").val() != '' && $("#park").val() != 'Enter the name of the park') {
			$("#subject").html('about '+$("#park").val());
			$("#subject-describe").html('your safari');
			$("#thinkabout").html('wildlife, scenery, weather, accommodations, food, transportation, your guide, other highlights');
			$("#rate-title").html('<span class="font-weight-normal">'+$("#park").val() + ' as a safari destination?</span>');
			$("#review-title").html(' about ' + $("#park").val());
			$("#when-title").html('<span class="font-weight-normal">go to ' + $("#park").val()+'?');
			$("#review_title-title").html(' about ' + $("#park").val());
		} else {
			$("#subject-describe").html('your safari');
			$("#rate-title").html('it?');
			$("#review-title").html('');
			$("#when-title").html('<b>go?</b>');
			$("#review_title-title").html('');
			$("#subject").html('');
			$("#parkscontainer").hide();
		}
		$("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
	} else if($("#reviewtype").val() == 'accommodation') {
		if(!$("#review_park_container").is(":visible") && window.location.pathname.indexOf('visited') == -1 && $("#hash").val() != "" && $("#accommodation").val() != "Enter the name of the accommodation") {
			$("#review_park_container").toggle('normal');
		}
		if($("#accommodation").val() != '' && $("#accommodation").val() != 'Enter the name of the accommodation') {
			$("#subject").html('about '+$("#accommodation").val());
			$("#subject-describe").html('your stay');
			$("#thinkabout").html('room, food, service, location, wildlife viewing activities');
			$("#rate-title").html('<span class="font-weight-normal">'+$("#accommodation").val() + '?</span>');
			$("#review-title").html(' about ' + $("#accommodation").val());
			$("#when-title").html('<span class="font-weight-normal">stay at ' + $("#accommodation").val()+'?');
			$("#review_title-title").html(' about ' + $("#accommodation").val());
		} else {
			$("#subject-describe").html('your safari');
			$("#rate-title").html('it?');
			$("#review-title").html('');
			$("#when").html('');
			$("#review_title-title").html('');
			$("#subject").html('');
		}
		
        $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
	} else if($("#reviewtype").val() == 'operator' && $("#operator").val() != '-') {
		$("#subject").html($("#operator option:selected").text());
		if($("#review_country_container").is(":visible")) {
			$("#review_country_container").toggle('normal');
		}
		if($("#review_park_container").is(":visible")) {
			$("#review_park_container").toggle('normal');
		}
		if($("#operator option:selected").val() == -1) {
			if($("#alternative-operator-name").val() != undefined) {
				$("#subject-describe").html($("#alternative-operator-name").val());
				$("#thinkabout").html('wildlife, scenery, weather, accommodations, food, transportation, your guide, other highlights');
				$("#rate-title").html('<span class="font-weight-normal">'+$("#alternative-operator-name").val() + ' as a safari operator?</span>');
				$("#review-title").html(' about ' + $("#alternative-operator-name").val());
				$("#when-title").html('<span class="font-weight-normal">go with ' + $("#alternative-operator-name").val()+'?');
				$("#review_title-title").html('<span class="font-weight-normal"> about ' + $("#operator option:selected").text());
			} else {
				$("#subject-describe").html('your safari');
				$("#rate-title").html('it?');
				$("#review-title").html('');
				$("#when").html('');
				$("#review_title-title").html('');
			}
		} else {
			$("#subject-describe").html($("#operator option:selected").text());
			$("#rate-title").html('<span class="font-weight-normal">'+$("#operator option:selected").text() + ' as a safari operator?</span>');
			$("#review-title").html(' about ' + $("#operator option:selected").text());
			$("#when-title").html('<span class="font-weight-normal">go with ' + $("#operator option:selected").text()+'?');
			$("#review_title-title").html('<span class="font-weight-normal"> about ' + $("#operator option:selected").text());
		}
        $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
	} else {
		$("#subject").html('');
		$("#subjectprefix").hide();
		$("#subject-describe").html('your safari');
		$("#thinkabout").html('wildlife, scenery, weather, accommodations, food, transportation, your guide, other highlights');
		if($("#review_country_container").is(":visible") && window.location.pathname.indexOf('visited') == -1) {
			$("#review_country_container").toggle('normal');
		}
		if($("#review_park_container").is(":visible") && window.location.pathname.indexOf('visited') == -1) {
			$("#review_park_container").toggle('normal');
		}
		$("#rate-title").html('it?');
	    $("#review-title").html('');
	    $("#when-title").html('<b>go?</b>');
	    $("#review_title-title").html('');
	    $("#otherparks-title").html('');
	    $("#review").unbind('click');
    	$("#review").bind('click', function() {
    		$("#review").attr('disabled', 'disabled').addClass('disabled');
            alert('Please select what your review is about.');
            $("#review").blur();
    	});	
	}
    $("#alternative-park-name-div").hide();
    $("#alternative-operator-name-div").hide();

	if($("#reviewtype").val() == 'park' && $("#park").val() == '-1') {
        if($("#alternative-park-name").attr('id') != undefined) {
            $("#alternative-park-name-div").show();
            if($("#alternative-park-name").val() != '' && $("#alternative-park-name").val() != 'Enter the name of the park here') {
                $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
            }
        } else {
            $("#about-container").append('<div id="alternative-park-name-div" class="alternative-name"><input type="text" class="grey" value="Enter the name of the park here" id="alternative-park-name" name="alternative-park-name" onkeyup="otherParkChange();" /></div>');
            $("#alternative-park-name").bind('focus', function() {
                if($(this).val() == 'Enter the name of the park here') {
                    $(this).val('');
                    $(this).removeClass('grey');
                }
            });
        }
        $("#alternative-park-name").bind('blur', function() {
            if($(this).val() == 'Enter the name of the park here' || $(this).val() == '') {
            	$("#review").bind('click', function() {
                    $("#review").attr('disabled', 'disabled').addClass('disabled');
                    alert('Please select what your review is about.');
                    $("#review").blur();
            	});	
            } else {
                $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
            }
        });
	}
	if($("#reviewtype").val() == 'operator' && $("#operator").val() == '-1') {
        if($("#alternative-operator-name").attr('id') != undefined) {
            $("#alternative-operator-name-div").show();
            if ($("#alternative-operator-name").val() != '' && $("#alternative-operator-name").val() != 'Enter the name of the operator here') {
                $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
            }
        } else {
            $("#about-container").append('<div id="alternative-operator-name-div" class="alternative-name"><input type="text" class="grey" value="Enter the name of the operator here" id="alternative-operator-name" name="alternative-operator-name" onkeyup="if($(this).val() == \'\') { $(\'#review-title\').html(\'\'); $(\'#rate-title\').html(\'it?\'); $(\'#when-title\').html(\'<b>go?</b>\'); $("#review_title-title").html(\'\'); } else { $(\'#review-title\').html(\'about \' + $(this).val()); $(\'#when-title\').html(\'<span class="font-weight-normal">go to \' + $(this).val() + \'?\'); $("#review_title-title").html(\'<span class="font-weight-normal"> about \' + $("#operator option:selected").text()); $(\'#rate-title\').html("<span class=\"font-weight-normal\">"+$(this).val() + \' as a safari operator?</span>\'); }" /></div>');
            $("#alternative-operator-name").bind('focus', function() {
                if ($(this).val() == 'Enter the name of the operator here') {
                    $(this).val('');
                    $(this).removeClass('grey');
                }
            });
        }
        $("#alternative-operator-name").bind('blur', function() {
            if($(this).val() == 'Enter the name of the operator here' || $(this).val() == '') {
            	$("#review").bind('click', function() {
                    $("#review").attr('disabled', 'disabled').addClass('disabled');
                    alert('Please select what your review is about.');
                    $("#review").blur();
            	});	
            } else {
                $("#review").unbind('click').removeAttr('disabled').removeClass('disabled');
            }
        });
	}	
}

function doValidation(id, type)
{
  var url = '/index/validateform/formname/'+id;
  var data = {};
  var re = new RegExp("^" + id);
  var count = 0;
  
   $("input").each(function()
   {
     if(re.test($(this).attr('name'))) {
       data[$(this).attr('name')] = $(this).val();
     }
   });
   $("textarea").each(function()
   {
     if(re.test($(this).attr('name'))) {
       data[$(this).attr('name')] = $(this).val();
     }
   });
  
  $.post(url,data,function(resp)
  {
	  var counter = 0;
	  for(respKey in resp){
		  if (respKey == 'indexOf') {
			  continue;
		  }
	      counter++;
	      var output = getErrorHtml(resp[respKey], respKey);
	      if(output != false) {
	    	  count = count + 1;
	      }
	      
	      if(respKey == 'newsletteremail') {
	    	if (output == false) {
	          	$('#errors'+respKey).remove();        	
	        } else {
	        	if (type != 'keyup') {
	                $('#errors'+respKey).remove();
	                $("#newslettersubmitbutton").parent().append(output); 
	        	}
	        }
	      } else {
	    	  	if (output == false) {
	    		  $('#errors'+respKey).remove();   	
		       } else {
		    	   
		    	   	if(resp['contactemail'] == undefined) {
		    	   		$('#errorscontactemail').remove();
		    	   	}
		    	   	
		    	   	if(resp['contactfeedback'] == undefined) {
		    	   		$('#errorscontactfeedback').remove();
		    	   	}
		        	if (type != 'keyup') {
	        			$('#errors'+respKey).remove();
		                $("#"+respKey).parent().append(output);
		        	}
		        }
	        
	      }
	  }

    if (counter == 0) {
    	
    	  $("input").each(function()
    			   {
    			     if(re.test($(this).attr('name'))) {
    			       $('#errors'+$(this).attr('name')).remove();
    			     }
    			   });
    			   $("textarea").each(function()
    			   {
    			     if(re.test($(this).attr('name'))) {
    			       $('#errors'+$(this).attr('name')).remove();
    			     }
    			   });
    			           	
    }
      
    if(count == 0 && type == 'submit') {
      if(id == 'newsletter') {
        saveNewsletter();
      } else {
        saveContact();
      }   
    }

  },'json');
}

function otherParkChange() {
	if($('#alternative-park-name').val() == '' || $('#alternative-park-name').val() == 'Enter the name of the park here') {
		$('#subject-describe').html('your safari');
		$('#selection-ok-button').hide();
		$('#subject').html('');
		$('#review-title').html('');
		$('#rate-title').html('it?');
		$('#when-title').html('<b>go?</b>');
		$('#review_title-title').html('');
	} else {
		$('#subject-describe').html($('#alternative-park-name').val());
		$('#selection-ok-button').show();
		$('#subject').html($('#alternative-park-name').val() + ' (' + $('#country option:selected').text() + ')');
		$('#review-title').html('about ' + $('#alternative-park-name').val());
		$('#rate-title').html('<span class="font-weight-normal">'+$('#alternative-park-name').val()+' as a safari destination?</span>');
		$('#when-title').html('<span class="font-weight-normal">go to '+$('#alternative-park-name').val()+'?</span>');
		$('#review_title-title').html(' about ' + $('#alternative-park-name').val());
	}
}

function getErrorHtml(formErrors , id)
{
  var o = '';
  for(errorKey in formErrors)
  {
      return '<span id="errors'+id+'" class="errors">' + formErrors[errorKey] + '</span>';
  }
  return false;
}

function saveNewsletter()
{
  var url = '/index/saveandmail';
  var data = {};
  
  data["newsletteremail"] = $("#newsletteremail").val();
  
  $.post(url,data,function(resp)
  {
      if(resp == 'OK') {
        // hide form, show success
        document.getElementById('wrapper').innerHTML = '<div class="thankyou"><span class="title">Thank you for subscribing!</span><br /><br />You can <a href="/">subscribe</a> again using another email address</div>';
      } else if(resp == 'NOTOK') {
    	  document.getElementById('wrapper').innerHTML = '<div class="sorry"><span class="title">Sorry, something went wrong.</span><br /><br />Please try to <a href="/">subscribe</a> again</div>';
      } else {
        // show form, show already subscribed
        document.getElementById('wrapper').innerHTML = '<div class="thankyou"><span class="title">You\'re already subscribed!</span><br /><br />You can <a href="/">subscribe</a> again using another email address</div>';
      }
  },'json');
}

function saveContact()
{
  var url = '/index/savecontact';
  var data = {};
  
  $("input").each(function()
  {
      data[$(this).attr('name')] = $(this).val();
  });
  $("textarea").each(function()
  {
      data[$(this).attr('name')] = $(this).val();
  });
  $.post(url,data,function(resp)
  {
      if(resp == 'OK') {
        // hide form, show success
        document.getElementById('contactform-content').innerHTML = '<div class="thankyou"><span class="title">Thank you for your feedback!</span><br /><br />You can <a href="/">go back</a> if you want to submit more feedback.</div>';
      }
  },'json');
}

function hideDropBoxes() 		{ $('#about-container').toggle('normal'); }
function showDropBoxes() 		{ $('#about-container').toggle('normal'); }
function hidePrefilledTitle() 	{ $('#title-about').show(); $('#changelink').hide(); }
function showPrefilledTitle() 	{ $('#title-about').hide(); $('#changelink').show(); }
function checkNotSure(field, mode) 	{
	if($('#'+field+'-check').attr('checked') == true && mode == 'on') {
		$('#'+field+'-score').val('');
		for(var i=1;i<=5;i++) {
			$('#'+field+'-'+i).attr('src','/images/star-off-small.png');
		}
	}
	if(mode == 'off') {
		$('#'+field+'-check').attr('checked', false);
	}
}
function getDirection(mouseposition) {
	  var myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	  
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	  
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	  
	    myHeight = document.body.clientHeight;
	  }
	  
	  return (myHeight - mouseposition);
}
function typeReviewerName() {
	if($("#reviewer_name").val().length > 1) {
		solveUnsolve("reviewername","solve");
		$("#reviewer_name").removeClass("field-error");
	} else {
		solveUnsolve("reviewername","unsolve");
	}
}

function extractParkAndCountry() {
	var regex = /([a-z-].+)\s\(([a-z-].+)\)/gi;
	var output = new Array();
	output = regex.exec($("#park").val());
	
	if(output != null && output[2] != '') {
		$.getJSON("/data/countryidbyname/name/" + output[2], function(data) {
			
			var country_id = data;
			$("input[name=pa_country]").val(country_id);
			
			$.getJSON("/data/parkidbyname/name/" + output[1] + "/country/" + country_id, function(data) {
			
				var park_id = data;
				$("input[name=park]").val(park_id);
				$("input[name=accommodation]").val('');
				if(country_id != null) {
					if($("#hash").val() != "") {
						getParksCheckboxes(country_id, park_id);
						$("#parkscontainer").show();
						if(!$("#review_country_container").is(":visible")) {
							$("#review_country_container").toggle('normal');
						}	
					}
				} else {
					if($("#review_country_container").is(":visible")) {
						$("#review_country_container").toggle('normal');
					}
					$("#parkscontainer").hide();
					$("input[name=pa_country]").val('');
					$("input[name=park]").val('');
					$("input[name=accommodation]").val('');
				}
			});
		});
		
		$("#review_country-title").html(output[2]);
		$("#otherparks-title").html(' in ' + output[2]);
		$("#rate-title").html('<span class="font-weight-normal">'+output[1] + ' as a safari destination?</span>');
		$("#review-title").html(' about ' + output[1]);
		$("#when-title").html('<span class="font-weight-normal">go to ' + output[1] + ' in ' + output[2]);
		$("#review_title-title").html(' about ' + output[1]);
	} else {
		if($("#review_country_container").is(":visible")) {
			$("#review_country_container").toggle('normal');
		}
		$("input[name=pa_country]").val('');
		$("input[name=park]").val('');
		$("input[name=accommodation]").val('');
		$("#parkscontainer").hide();
	}
}

function extractAccommodationParkAndCountry() {
	var regex = /([a-z-].+)\s\(([a-z-].+)\)/gi;
	var output = new Array();
	output = regex.exec($("#accommodation").val());
	
	if(output != null && output[2] != '') {
		$.getJSON("/data/idsbyaccommodationname/name/" + output[1] + "/country/" + output[2], function(data) {
			
			if(data != null) {
				var country_id = data[0]['country_id'];
				$("input[name=pa_country]").val(country_id);
				var park_id = data[0]['park_id'];
				$("input[name=park]").val(park_id);
				var accommodation_id = data[0]['accommodation_id'];
				$("input[name=accommodation]").val(accommodation_id);
				var park_name = data[0]['park_name'];
				
				if(country_id != null ) {
					if($("#hash").val() != "") {
						getParksCheckboxes(country_id, park_id);
						$("#review_country-title").html(output[2]);
						if(!$("#review_country_container").is(":visible")) {
							$("#review_country_container").toggle('normal');
						}
						$("#review_park-title").html(park_name);
					}
				} else {
					if($("#review_country_container").is(":visible")) {
						$("#review_country_container").toggle('normal');
					}
					$("input[name=pa_country]").val('');
					$("input[name=park]").val('');
					$("input[name=accommodation]").val('');
				}
			} else {
				if($("#review_country_container").is(":visible")) {
					$("#review_country_container").toggle('normal');
				}
				if($("#review_park_container").is(":visible")) {
					$("#review_park_container").toggle('normal');
				}
			}
		});
		
		$("#rate-title").html('<span class="font-weight-normal">'+output[1] + '?</span>');
		$("#review-title").html(' about ' + output[1]);
		$("#when-title").html('<span class="font-weight-normal">go to ' + output[1] + ' in ' + output[2]);
		$("#review_title-title").html(' about ' + output[1]);
	} else {
		if($("#review_country_container").is(":visible")) {
			$("#review_country_container").toggle('normal');
		}
		if($("#review_park_container").is(":visible")) {
			$("#review_park_container").toggle('normal');
		}
		$("input[name=pa_country]").val('');
		$("input[name=park]").val('');
		$("input[name=accommodation]").val('');
	}
}

function extractOperator() {
	var regex = /([a-z-].+)\s\(([a-z-:\/].+)\)/gi;
	var output = new Array();
	output = regex.exec($("#operator_name").val());
	
	if(output != null && output[2] != '') {
		$.getJSON("/data/operatoridbyurl/url/" + output[2], function(data) {
			
			var operator_id = data;
			
			
			if(operator_id != null) {
				$("input[name=operator_id]").val(operator_id);
			} else {
				$("input[name=operator_id]").val('');
			}
		});
		
	} else {
		$("input[name=operator_id]").val('');
	}
}

function setRatingTexts($type) {
	if($type == 'accommodation') {
		$("#rating-a-text").html('Location');
		$("#rating-b-text").html('Service');
		$("#rating-c-text").html('Room &amp; Bed');
		$("#rating-d-text").html('Food');
		$("#bush-vibe-explanation").hide();
		$("#location-explanation").show();
	} else {
		$("#rating-a-text").html('Wildlife');
		$("#rating-b-text").html('Scenic beauty');
		$("#rating-c-text").html('Bush vibe');
		$("#rating-d-text").html('Birding');
		$("#bush-vibe-explanation").show();
		$("#location-explanation").hide();
	}
}
