/**
 * Makes the call to rate a review
 *
 * @example request_ReviewRatings(10,5)
 * @param interger $rating  The rating the user selected
 * @param interger $review_id The ID of the review being rated
 */
function request_review_ratings($rating,$review_id)
{
    var params = { "rating":$rating, "review_id":$review_id };
    var json = new JSON;
    json.request('review_rating',params,callback_review_ratings,'','/libs/JSON/review_actions.php');
}

/**
 * The Callback actions for request_review_ratings
 * It displays the rating of a review
 *
 * @param array $data [hasRating, rid, review_id, mustread, helpful, nothelpful]
 */
function callback_review_ratings($data)
{
    var hasRating = $data.hasRating;
    var review_id = $data.rid;

    if($data.err_code){
        error_handler_by_id($data.err_code);
    }else{
        $('#reviewrating'+ review_id +'_0').text($data.mustread);
        $('#reviewrating'+ review_id +'_1').text($data.helpful);
        $('#reviewrating'+ review_id +'_2').text($data.nothelpful);
    }
}

/**
 * @var array Keeps track of all review on the stage as well as the page
 */
var calledReviews = new Array();
var currentReviewPages = new Array();


/**
 * If the page isnt already loaded load it
 * Makes the call to get a page of reviews
 *
 * @param interger $id The ID of the listing the reviews belongs to
 * @param {string} $section_type Declares the type of page the user is on. This will determine the content in the element
 * @param interger $page  The Page Number To Load
 * @param boolean $override Will call in the content no matter what (even if the element is already loaded)
 */
function request_review_page($id,$section_type,$page,$override) {
    if( $('#reviews_wrapper') && ($override || !currentReviewPages[$id+"-"+$page]) ){
        var review_wrapper = $('#reviews_wrapper')[0];
        enterPreLoader(review_wrapper);
        var params = {
            "listing_id":$id,
            "page":$page
        };
        var json = new JSON;
        json.request('review_page',params,callback_review_page,$section_type,'/libs/JSON/review_actions.php');
        currentReviewPages[$id+"-"+$page] = $id+"-"+$page;
    }
}

/**
 * The Callback actions for request_review_page
 * It displays a full page of reviews
 * Resets the calledReviews array
 * It writes the HTML to a DIV with the ID reviews_wrapper
 * Then loops though an array of each review and embeds the flash files
 * If $data.full_review is set the element is set in calledReviews
 *
 * @param array $data [html,reviews[],num_reviews]
 */
function callback_review_page($data)
{
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
        loadScript('{$config.structure.jsurl}content_display/add_review.js');
        calledReviews = new Array()

        $('#reviews_wrapper').html($data.html);

        if($('#review_buisness_form_'+$data.id)[0]){
            inlinePopups['square_popup_add_review_'+$data.id] = true;

            var params = { wmode: "transparent", quality: "high" }
            var flashvars = {};
            flashvars.title        = "REVIEW THIS BUSINESS";

            swfobject.embedSWF('/swf/popup_h1_square.swf', 'popup_h1_square_popup_add_review_'+$data.id, '500', '28', '8', '', flashvars, params);

            rating_stars('/swf/rating.swf','hidden_field','rating_element',0,$data.id,140,30);

            // I hate this so very much.
            var rating = document.createElement("input");                       
            rating.id    = "rating";
            rating.name  = "params[4]";
            rating.type  = "hidden";
            if($data.rating){
                rating.value = $data.rating;
            }else{
                rating.value = 0;
            }
            rating.onMouseDown = function(){ clearDragObject(); }
            $('#rating_hidden_holder').append(rating);

        }

        for(i=0;i<$data.num_reviews;i++){
            if($data.reviews[i].full_review){
                calledReviews[$data.reviews[i].review_id] = $data.reviews[i].review_id;
            }
            var flashDivID = "review_rating_"+$data.reviews[i].review_id;

            var params = { wmode: "transparent", quality: "high" }
            var flashvars = {};
            flashvars.rating        = $data.reviews[i].rating;
            flashvars.id            = $data.reviews[i].review_id;
            flashvars.rating_type   = "review";

            swfobject.embedSWF("/swf/rating.swf", flashDivID, "70", "15", "6", '', flashvars, params);
        }
    }
}

/**
 * If the review isnt on stage and the function isnt set to overide this uses open_review_element to show details
 * Otherwise it will create a new review element as the first child in 'reviews_inner' or use the one already on stage
 * It sets the className and makes the AJAX call for the HTML needed
 *
 * @example request_review_details(5,null,true,'listing_details')
 * @param {interger} $review_id  The ID of the review being requested
 * @param {string} $display_type Declaring the type of display(review_full,review_short) of the element
 * @param {boolun} $override Tells the function to get data from the server, no matter what
 * @param {string} $section_type Declares the type of page the user is on. This will determine the content in the element
 */
function request_review_details($review_id,$display_type,$override,$section_type, $listing_id) {
    if ($override || !calledReviews[$review_id]) {
        var reviewHolder = $("#review_element_"+$review_id)[0];

        // If there is no element create one
        if (!reviewHolder) {
            if (!$('#reviews_inner')[0] && $listing_id) {
                // Ok, am I on a listing details page?
                if ($('#reviews_wrapper')[0]) {
                    // Good...
                    return request_review_page($listing_id, $section_type, 1, true);
                }
            }
            if ($('#reviews_inner')[0]) {
                var clearAll = document.createElement('div');
                clearAll.className="clearAll";
                var reviewHolder = document.createElement('div');
                reviewHolder.id = "review_element_"+$review_id;
                reviewHolder.className = "review_full";
                $('#reviews_inner')[0].insertBefore(clearAll, $('#reviews_inner').firstChild);
                $('#reviews_inner')[0].insertBefore(reviewHolder, $('#reviews_inner').firstChild);
                $('#reviews_inner')[0].className ="gen_box_content no_bottom";
            }
        } else {
            var reviewHolder = $("#review_element_"+$review_id)[0];
        }
        // Only if it all actually worked...
        if (reviewHolder) {
            var displayFlag = null;
            if($display_type){ displayFlag = $display_type; }else{ displayFlag = "review_full"; }
            reviewHolder.className = displayFlag;

            enterPreLoader(reviewHolder);

            var params = {"review_id":$review_id};
            var json=new JSON;
            json.request('review_details',params,callback_details_ListingReview,$section_type,'/libs/JSON/review_actions.php') ;
            calledReviews[$review_id] = $review_id;
        }
    } else {
        open_review_element($review_id);
    }
}



/**
 * If the review isnt on stage and the function isnt set to overide this uses open_review_element to show details
 * Otherwise it will create a new review element as the first child in 'reviews_inner' or use the one already on stage
 * It sets the className and makes the AJAX call for the HTML needed
 *
 * @example request_review_details(5,null,true,'listing_details')
 * @param {interger} $review_id  The ID of the review being requested
 * @param {string} $display_type Declaring the type of display(review_full,review_short) of the element
 * @param {boolun} $override Tells the function to get data from the server, no matter what
 * @param {string} $section_type Declares the type of page the user is on. This will determine the content in the element
 */
function request_abandoned_review_details($review_id,$display_type,$override,$section_type, $listing_id) {
    if ($override || !calledReviews[$review_id]) {
        var reviewHolder = $("#review_element_"+$review_id)[0];

        // If there is no element create one
        if (!reviewHolder) {
            if (!$('#reviews_inner')[0] && $listing_id) {
                // Ok, am I on a listing details page?
                if ($('#reviews_wrapper')[0]) {
                    // Good...
                    return request_review_page($listing_id, $section_type, 1, true);
                }
            }
            if ($('#reviews_inner')[0]) {
                var clearAll = document.createElement('div');
                clearAll.className="clearAll";
                var reviewHolder = document.createElement('div');
                reviewHolder.id = "review_element_"+$review_id;
                reviewHolder.className = "review_full";
                $('#reviews_inner')[0].insertBefore(clearAll, $('#reviews_inner').firstChild);
                $('#reviews_inner')[0].insertBefore(reviewHolder, $('#reviews_inner').firstChild);
                $('#reviews_inner')[0].className ="gen_box_content no_bottom";
            }
        } else {
            var reviewHolder = $("#review_element_"+$review_id)[0];
        }
        // Only if it all actually worked...
        if (reviewHolder) {
            var displayFlag = null;
            if($display_type){ displayFlag = $display_type; }else{ displayFlag = "review_full"; }
            reviewHolder.className = displayFlag;

            enterPreLoader(reviewHolder);

            var params = {"review_id":$review_id};
            var json=new JSON;
            json.request('review_abandoned_details',params,callback_details_ListingReview,$section_type,'/libs/JSON/review_actions.php') ;
            calledReviews[$review_id] = $review_id;
        }
    } else {
        open_review_element($review_id);
    }
}


function request_review_details_short($review_id) {
     var params = {"review_id":$review_id, "type":"short"};
     var json=new JSON;
     json.request('review_details',params,callback_details_ListingReview_short,'','/libs/JSON/review_actions.php') ;
            
}

/**
 * The Callback actions for request_review_details
 * It adds the content to the reviewHolder
 * Embeds the rating starts
 * Adds the ID to calledReviews array
 *
 * @param array $data [review_id, html, rating]
 */
function callback_details_ListingReview($data) {
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
        $("#review_element_"+$data.review_id).html($data.html);
        var flashDivID = "review_rating_"+$data.review_id;
        var params = { wmode: "transparent", quality: "high" }
        var flashvars = { rating: $data.rating, id: $data.review_id, rating_type:"review" };
        swfobject.embedSWF("/swf/rating.swf", flashDivID, "70", "15", "6", '', flashvars, params);


        calledReviews[$data.review_id] = $data.review_id;
    }
}

/**
 * The Callback actions for request_review_details
 * It adds the content to the reviewHolder
 * Embeds the rating starts
 * Adds the ID to calledReviews array
 *
 * @param array $data [review_id, html, rating]
 */
function callback_details_ListingReview_short($data) {
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
//      $("#review_element_"+$data.review_id).html($data.html);
        $("#review_element_"+$data.review_id).removeClass().addClass("review_short");
        $("#review_short_desc_"+$data.review_id).html($data.short_desc);
    }
}

/**
 * Removing a review element completely from the DOM
 * Also its ID from the array of review elements on stage
 *
 * @param integer $elementID The ID of the DIV
 * @example remove_review_element(this.id);
 */
function remove_review_element($elementID)
{
    var reviewHolder = $("#review_element_"+$elementID)[0];
    var reviewWrapper = $("#"+reviewHolder.parentNode.id)[0];
    calledReviews[$elementID] = false;
    reviewWrapper.removeChild(reviewHolder);
}

/**
 * Closeses a review if it is already on the stage
 *
 * @param integer $elementID The ID of the DIV
 * @example close_review_element(this.parentNode.id);
 */
function close_review_element($elementID, $text)
{
    $("#review_element_"+$elementID).removeClass().addClass("review_short");
//  $("#review_short_desc_"+$elementID).html($text);
    return false;
}

/**
 * Opens a review if it is already on the stage and has all content needed
 *
 * @param integer $elementID The ID of the DIV
 * @example open_review_element(this.parentNode.id);
 * @todo make it request content if its not already populated
 */
function open_review_element($elementID)
{
    $("#review_element_"+$elementID).removeClass().addClass("review_full");
    return false;
}

/**
 * Is called on submit of the add comments form
 *
 * @param object $element
 * @example review_comment(this);
 */
function review_comment($element){
    var params = new Array();
    params[0] = $('#title_comment').attr('value');
    params[1] = $('#comment').attr('value');
    params[2] = $('#review_id').attr('value');
    params[3] = getPopUpWrapperId($element);
    params[4] = $('#review_comment_id').attr('value');
    var json = new JSON;
    json.request('review_comment',params,callback_review_comment,'','/libs/JSON/review_actions.php');
}

/**
 * Call back for review_comment
 * Updates the current review
 * Closes The Popup
 *
 * @param array $data [elementID, review_id]
 */
function callback_review_comment($data) {
    if ($data.err_code) {
        error_handler_by_id($data.err_code, $data.err_str);
    }else{
        // Calling to update the review
        request_review_details($data.review_id,null,true);
        popup_close_all();
    }
}


/**
 * Delete a user's review
 *
 * @param integer Review id
 * @example delete_review( review_id );
 */
function delete_comment( r_id ){
    if( confirm('Do you really want to delete this review ?') ) {
        var params = new Array();
        params[0] = r_id;
        var json = new JSON;
        json.request('delete_review',params,callback_delete_review,'','/libs/JSON/review_actions.php');
    }
}


/**
 * Delete a user's review
 *
 * @param integer Review id
 * @example delete_review( review_id );
 */
function delete_abandoned_review( r_id ){
    if( confirm('Do you really want to delete this review ?') ) {
        var params = new Array();
        params[0] = r_id;
        var json = new JSON;
        json.request('delete_abandoned_review',params,callback_delete_review,'','/libs/JSON/review_actions.php');
    }
}


function callback_delete_review( $data ) {
    p = $('#review_element_' + $data['r_id'])[0].parentNode;
    p.removeChild( $('#review_element_' + $data['r_id'])[0] );
}

/**
 * Delete a user's review
 *
 * @param integer Review id
 * @example delete_review( review_id );
 */
function publish_abandoned_review( r_id ){
    if( confirm('Do you really want to publish this review ?') ) {
        var params = new Array();
        params[0] = r_id;
        var json = new JSON;
        json.request('publish_abandoned_review',params,callback_publish_review,'','/libs/JSON/review_actions.php');
    }
}


function callback_publish_review( $data ) {
        p = $('#review_element_' + $data['r_id'])[0];
        p.innerHTML = "Review was published successfully!" ;
}


/**
 * Delete a user's review comment
 *
 * @param integer Comment id
 * @example delete_review_comment( review_id );
 */
function delete_review_comment( r_id, rc_id ) {
    if( confirm('Do you really want to delete this comment ?') ) {
        var params = new Array();
        params[0] = r_id;
        params[1] = rc_id;
        var json = new JSON;
        json.request('delete_comment',params,callback_delete_comment,'','/libs/JSON/review_actions.php');
    }
}

function callback_delete_comment( $data ) {
        if($data['rc_id']) {
            p = $('#review_comment_element_' + $data['rc_id'])[0].parentNode;
            p.removeChild( $('#review_comment_element_' + $data['rc_id'])[0] );
            if($data['r_id'] && ($data['num_comments']==0 || $data['num_comments']==false) ) {
                        $('#comments_title_' + $data['r_id']).html("");
                }
        }

}

/**
* Calls the stuff responsible for making a facebook feed thing
* @param string $details {"review_id":###, "company_name":"...", "review_text":"...", "review_text_full":"..."}
*/
function publish_to_facebook($details) {
    FB.ensureInit(function() {
        FB.Connect.showFeedDialog(48531151643, $details, null, null, FB.FeedStorySize.shortStory);
    });
}

/**
 * Handle hover event for stars
 */
function starHover(e) {
    var myPosition = $(this).offset();
    var difference = e.clientX - myPosition.left;
    if (difference > 90) { $(this).children("img").css("marginTop", -200); }
    else if (difference > 80) { $(this).children("img").css("marginTop", -180); }
    else if (difference > 70) { $(this).children("img").css("marginTop", -160); }
    else if (difference > 60) { $(this).children("img").css("marginTop", -140); }
    else if (difference > 50) { $(this).children("img").css("marginTop", -120); }
    else if (difference > 40) { $(this).children("img").css("marginTop", -100); }
    else if (difference > 30) { $(this).children("img").css("marginTop", -80); }
    else if (difference > 20) { $(this).children("img").css("marginTop", -60); }
    else if (difference > 10) { $(this).children("img").css("marginTop", -40); }
    else if (difference > 00) { $(this).children("img").css("marginTop", -20); }
}

/**
 * Handle click event for stars
 */
function starClick(e, that) {
    var myPosition = $(that).offset();
    var difference = e.clientX - myPosition.left;
    var rating=0;
    if (difference > 90) { rating = 10; }
    else if (difference > 80) { rating = 9; }
    else if (difference > 70) { rating = 8; }
    else if (difference > 60) { rating = 7; }
    else if (difference > 50) { rating = 6; }
    else if (difference > 40) { rating = 5; }
    else if (difference > 30) { rating = 4; }
    else if (difference > 20) { rating = 3; }
    else if (difference > 10) { rating = 2; }
    else if (difference > 00) { rating = 1; }
	setRatingValue(rating);
}

/**
 * Reset the star value, handles mouse out event for stars
 */
function starReset(that) {
    var rating = getRatingValue();
    if (rating == 10) { $(that).children("img").css("marginTop", -200); }
    else if (rating == 9) { $(that).children("img").css("marginTop", -180); }
    else if (rating == 8) { $(that).children("img").css("marginTop", -160); }
    else if (rating == 7) { $(that).children("img").css("marginTop", -140); }
    else if (rating == 6) { $(that).children("img").css("marginTop", -120); }
    else if (rating == 5) { $(that).children("img").css("marginTop", -100); }
    else if (rating == 4) { $(that).children("img").css("marginTop", -80); }
    else if (rating == 3) { $(that).children("img").css("marginTop", -60); }
    else if (rating == 2) { $(that).children("img").css("marginTop", -40); }
    else if (rating == 1) { $(that).children("img").css("marginTop", -20); }
    else {$(that).children("img").css("marginTop", 0);}
}

/**
 * Set this to 1 if you want to allow 0 stars
 * It's not a good idea since people will forget to rank
 */
allowZeroStars = 0;


/**
 * Sets the rank to 0, when allowZeroStars is = 1
 */
function starSetToZero(that) {
	if(allowZeroStars == 1){	
		$(that).children("img").css("marginTop", 0);
		setRatingValue(0);
	}
}

/**
 * Set the value of stars in a hidden input element
 */
function setRatingValue(value){
	 $('#rating').attr('value', value);
}

/**
 * get the value of stars out of a hidden input element
 */
function getRatingValue(){
	return $('#rating').attr('value');
}
