var nRating=0;
var nSubrating=[0,0,0,0];
var idDialog;
var idRating;
var idOverall;
var rateItLinkId="";
var rateLoggedIn = false


function call_rate_it(logged_in,event,listing_type,listing_id,rateit_link_id) {
    var show_rating_dialog = !hasUserRated(listing_type,listing_id);
    if (show_rating_dialog){
        showRateItDialog(event,'rating_dialog',listing_type,listing_id, rateit_link_id, logged_in);
    }
}


function iniDialog(id, idOv){
	idDialog = id;
	idOverall = idOv;
}

function dialogManager(e, id, position){
    closeDialog('review_dialog');
    closeDialog('thank_you_dialog');
    closeDialog('already_rated_dialog');
    closeDialog('already_reviewed_dialog');
    $(id).style.display='block';

	/*
	switch(rating){
	case 1:
	  $('ratingtx').setHTML('Liked it');
	  break
	case 2:
	  $('ratingtx').setHTML('Really Liked it');
	  break
	case 3:
	  $('ratingtx').setHTML('Loved it');
	  break
	case 4:
	  $('ratingtx').setHTML('Really Loved it');
	  break
	case 5:
	  $('ratingtx').setHTML('Favorite');
	  break
	default:
	  $('ratingtx').setHTML('Liked it');
	  }
	*/
	
    if ( typeof position == "undefined" ) {
        var posx = 0; 
		var posy = 0;
        if (!e) var e = window.event;
        if(e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }else if(e.clientX || e.clientY) {
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
		
		// Let's insert a relative pop up flyout that plays within the window
		// we want to subtract from the width of the browser screen with the coordinates of the mouse click
		// if that value is less than the approxiamate width of the div box then reposition the div box
		var windowWidth;
		if (self.innerWidth) { 
			// All except Explorer
			windowWidth = self.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			// Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
		} else if (document.body) {
			// Other Explorers
			windowWidth = document.body.clientWidth;			
		}
		
		if((windowWidth - posx) < $(id).getDimensions().width) {
			// let's center on right side of div
			$(id).style.top = (posy+20)+'px';
			$(id).style.left = (posx-($(id).getDimensions().width-25))+'px';
			
			// let's reposition the top triangle thing
			$(id).down(".dialog-pest", 0).setStyle({'right' : '15px', 'left' : ''});
			return;
		} else {
			// Reset
			$(id).down(".dialog-pest", 0).setStyle({'left' : '15px', 'right' : ''});
		}
		
        $(id).style.top = (posy+20)+'px';
        $(id).style.left = (posx-20)+'px';
    }
    else {
        $(id).style.top = position[0];
        $(id).style.left = position[1];
    }
}

function closeRatingDialogs(){
    closeDialog('rating_dialog');
    closeDialog('review_dialog');
    closeDialog('thank_you_dialog');
    closeDialog('already_rated_dialog');
    closeDialog('already_reviewed_dialog');
    reset_review_fields();
}

function closeDialog(id, clear_review){
	if($(id)) {
		$(id).hide();
	}
    if ( typeof clear_review != "undefined" ) {
        reset_review_fields();
    }
}

function showAlreadyRatedDialog(evnt) {
    dialogManager(evnt, 'already_rated_dialog');
}

function showAlreadyReviewedDialog(evnt) {
    dialogManager(evnt, 'already_reviewed_dialog');
}

function showReviewDialog(evnt, dialog_id, rating_id, logged_in) {
    rateLoggedIn = logged_in;
    var rating = $F('listing_rating');
    nRating = rating;
	rating_element = $(rating_id);
	if (rating_element) $(rating_id).style.width=(rating*18)+'px';
    dialogManager(evnt, dialog_id);
	expandReviewForm();
//     if ($('thank_you')) Element.hide($('thank_you'));
//     if ($('write_a_review')) Element.show($('write_a_review'));
//     if ($('review_errors')) Element.hide($('review_errors'));
//     if ($('overall-rating')) Element.show($('overall-rating'));
}

function expandReviewForm() {
	var listing_id = $F('listing_id');
	var query      = 'listing_id=' + listing_id;
	new Ajax.Request('/new_review', {method:'post', postBody:query, asynchronous:false, onComplete:function(request){eval(request.responseText)} });
}

function hasUserRated(event,listing_type,listing_id,rateit_link_id) {
    var query      = 'listing_type=' + listing_type + '&listing_id=' + listing_id + '&rateit_link_id=' + rateit_link_id;
    var status = false;
    new Ajax.Request('/has_rated', {
        method:'post', postBody:query,
        asynchronous:false,
        onComplete:function(request){
            eval(request.responseText);
        }
    });
}

function showRateItDialog(evnt, dialog_id, listing_type, listing_id, rateit_link_id, logged_in) {
    //alert('showRateItDialog' + evnt);
    if ( typeof listing_type != "undefined" ) {
        $('listing_type').value=listing_type;
        if ($("rating_data_accommodation")) Element.hide("rating_data_accommodation");
        if ($("rating_data_restaurant")) Element.hide("rating_data_restaurant");
        if ($("rating_data_attraction")) Element.hide("rating_data_attraction");
        if ($("rating_data_nightlife_spot")) Element.hide("rating_data_nightlife_spot");
        if ($("rating_data_store")) Element.hide("rating_data_store");
    }
    if ( typeof listing_id != "undefined" ) {
        $('listing_id').value=listing_id;
    }
    if ( typeof rateit_link_id != "undefined" ) {
        rateItLinkId=rateit_link_id;
    }
    showRatingDialog(evnt, dialog_id, false, logged_in);
}

function showRatingDialog(evnt, dialog_id, show_errors, logged_in, position) {
    if ($('review_dialog_title')) Element.hide($('review_dialog_title'));
	if ($('thank_you')) Element.show($('thank_you'));
	if ($('overall-rating')) Element.hide($('overall-rating'));
	if ($('write_a_review')) Element.hide($('write_a_review'));
	
	if($(dialog_id)) {
		if($('rating_dialog')) {
			var childPest = $('rating_dialog').down(".dialog-pest", 0);			
			$(dialog_id).down(".dialog-pest", 0).setStyle({'right' : childPest.getStyle('right'), 'left' : childPest.getStyle('left')})
		}
	}
	
    if (show_errors==true)
        Element.show($('review_errors'));
    else
        Element.hide($('review_errors'));

    var listing_type = $('listing_type').value;
    if ( typeof listing_type != "undefined" ) {
        var rating_data_div = "rating_data_"+ listing_type.toLowerCase();
        if ( $(rating_data_div) ) Element.show(rating_data_div);
    }
    rateLoggedIn = logged_in;
    dialogManager(evnt, dialog_id, position);
}

function submit_rating_with_position(event, rating, dialog_id, rating_id1, rating_id2){
    var position = new Array();
    position[0] = $('rating_dialog').style.top;
    position[1] = $('rating_dialog').style.left;
    submit_rating(event, rating, dialog_id, rating_id1, rating_id2, position)
}

function submit_my_rating(rating) {
	if(rating && $('listing_type') && $('listing_id')) {
	    var query = 'listing_type='+$F('listing_type')+'&listing_id='+$F('listing_id')+'&listing_rating='+rating;
	    new Ajax.Request('/rate', {method:'post', postBody:query, asynchronous:true});
	}
}

function submit_rating(event, rating, dialog_id, rating_id1, rating_id2, postition){
    rate(rating,rating_id1,rating_id2);
    disable_rate(event);
    showRatingDialog(event, dialog_id, false, rateLoggedIn, postition)

    $('listing_rating').value = rating;

    var listing_rating=rating;
    var listing_type=$F('listing_type');
    var listing_id=$F('listing_id');
    if (listing_rating != "undefined" ) {
        var query = 'listing_type='+listing_type+'&listing_id='+listing_id+'&listing_rating='+listing_rating;
        //alert(query)
        new Ajax.Request('/rate', {method:'post', postBody:query, asynchronous:true});
    }
}

function rate(rating, id1, id2){	
    nRating = rating;
    update_rating_stars(rating, id1, id2);
}


function overallRate(rating,id1){
	nRating = rating;
	$('listing_rating').value = nRating;
    updateRating(rating, id1);
}

function rate_subrating(rating, index, id1, id2){
    nSubrating[index] = rating;
    update_rating_stars(rating, id1, id2);
}

function update_rating_stars(width, id1, id2){
    width = width * 18;
    if ( id1 && $(id1) ) {
        $(id1).style.width=width+'px';
    }
    if ( id1 && $(id1+'2') ) {
        $(id1+'2').style.width=width+'px';
    }
    if ( id2 && $(id2) ) {
        $(id2).style.width=width+'px';
    }
}

function updateRating(rating,rating_id) {
	if (rating > 0)
     $(rating_id).style.width=(rating*18)+'px';
	
}

function submit_review(login,action) {
    $('review_action').value = action
    $('listing_subrating').value = nSubrating;
    $('review_form').onsubmit();

    //var errors = validate_review(create_account);

    // 
    //if (errors==true) {
    //  Element.show($('review_errors'));
    //  return false;
    //

	//if(rateLoggedIn) dialogManager(event, thank_you_id, position);
	//disable_review(event);

//     var listing_type=$F('listing_type');
//     var listing_id=$F('listing_id');
//     var listing_rating=nRating;
//     var review_title=escape($F('review_title'));
//     var review_text=escape($F('review_text'));
// 	var query = 'listing_type='+listing_type+'&listing_id='+listing_id;
// 	var screen_name = escape($F('screen_name'));
// 	var email = escape($F('email'));
// 	var password = escape($F('password'));
//     if (listing_rating >0 ) {
//         $('listing_rating').value=listing_rating;
// 		query += '&listing_rating='+listing_rating;
//         if ($(rating_id)) {
//             $(rating_id).style.width=(listing_rating*18)+'px';
//         }
//         disable_rate(event);
//     }
// 	query += '&listing_subrating='+nSubrating[1]+',';
// 	query += nSubrating[2]+',';
// 	query += nSubrating[3];
// 	query += '&review[review_text]='+review_text;
// 	query += '&review[review_title]='+review_title;
// 	query += '&email='+email;
// 	query += '&password='+password;
// 	query += '&screen_name='+screen_name;
    //reset_review_fields();
//	new Ajax.Request('/review', {method:'post', postBody:query, asynchronous:true, onComplete:function(transport) { eval(transport.responseText) } });
}

function reset_review_fields() {
    var screen_name = $F('user_screen_name');
    if ( '' == screen_name ) {
        screen_name = 'Pick a Screen Name';
    }
    reset_review_field('review_title','Your Review Title');
    reset_review_field('review_text','Your Review');
}

function reset_review_field(element_id, value) {
    var default_fontStyle = "italic";
    var default_color = "#999999";
    var element = $(element_id);
    if (element) {
        element.value = value;
        element.style.fontStyle = default_fontStyle;
        element.style.color = default_color;
    }
}

function disable_rate(event) {
    var nothing = already_done_link(event);
    if ($('rateit_link')) $('rateit_link').onclick=nothing;
    if ($('rateit_link_2')) $('rateit_link_2').onclick=nothing;
    if ($('overall_in_1')) {
        $('overall_in_1').onclick=nothing;
        $('overall_in_1').addClassName("no-star");
        $('overall_in_1').removeClassName("one-star");
    }
    if ($('overall_in_2')) {
        $('overall_in_2').onclick=nothing;
        $('overall_in_2').addClassName("no-star");
        $('overall_in_2').removeClassName("two-stars");
    }
    if ($('overall_in_3')) {
        $('overall_in_3').onclick=nothing;
        $('overall_in_3').addClassName("no-star");
        $('overall_in_3').removeClassName("three-stars");
    }
    if ($('overall_in_4')) {
        $('overall_in_4').onclick=nothing;
        $('overall_in_4').addClassName("no-star");
        $('overall_in_4').removeClassName("four-stars");
    }

    if  (rateItLinkId!="") {
        if ($(rateItLinkId)) $(rateItLinkId).onclick=nothing;
        rateItLinkId="";
    }
}

function already_done_link(event) {
    var onclick_handler = function(event) { showAlreadyRatedDialog(event); return false;}

    return onclick_handler;
}

function do_nothing() {
  return false;
}

function disable_review (event) {
    if ($('review_link')) $('review_link').onclick = already_done_link(event);
}

function validate_review(create_account) {
    var error_msg_div = $('error_messages');
    var review_title=$F('review_title');
    var review_text = $F('review_text');
	var screen_name = $F('screen_name');
	var email = $F('email');
	var password = $F('password');
    var errors = false;
    var msg = '';
    if ( !(nRating>0) ) {
        msg = msg + "<li>Overall rating</li>";
        errors = true;
    }
    if (review_title=="" || review_title=="Your Review Title") {
        msg = msg + "<li>Your review title</li>";
        errors = true;
    }
    if (review_text=="" || review_text=="Your Review") {
        msg = msg + "<li>Your review</li>";
        errors = true;
    }
    if ( $('review_agree').checked==false && create_account ) {
        msg = msg + "<li>Agree to Terms and Service</li>";
        errors = true;
    }
    if ( create_account && screen_name == "") {
        msg = msg + "<li>Screen name</li>";
        errors = true;
    }
    if (msg!='') {
        msg='<ul class="error_messages">'+msg+'</ul>';
    }
    error_msg_div.innerHTML = msg;
    return errors;
}

function rateMouseOver(index) {
	var elements = $('ratings_container').getElementsByTagName('A');
	for(i=1;i<5;i++) {
		var currentElement = elements[i-1]
		var className = '';
		var selected = $('selected_index').value;
		if(selected > -1) {
			if(i<=selected&&i<=index)className='selectedover';
			else if(i<=selected&&i>index)className='selectedless';
			else if(i>selected&&i<=index)className='over';
			else if(i>selected&&i>index)className='';
		} else {
			if(i<=this.index)className='over'
		}
		currentElement.className=className;
	}
}

function rateMouseOut(index) {
	var elements = $('ratings_container').getElementsByTagName('A');
	for(i=1;i<5;i++) {
		var currentElement = elements[i-1];
		var selected = $('selected_index').value;
		if(selected!=-1&&selected>=i){
			var className='selected';
		} else {
			var className='';
		}
		currentElement.className = className;
	}
}



