/**
 * @author frashid
 * 
 */

var cdpVoteCount;
var targetDivId = 'thumbs_count_uml';
// whichReferrer set in referrers.js, isUGC set in page
if(isUGC == false && whichReferrer != 'google') {
	targetDivId = 'thumbs_count';
}

var cdpVoted = false;

function ShowRateIt(){
	if(!cdpVoted){
		cdpVoteCount = document.getElementById(targetDivId).innerHTML;
		document.getElementById(targetDivId).innerHTML = "Rate it";
	}
}

function HideRateIt(){
	if(!cdpVoted){
		document.getElementById(targetDivId).innerHTML = cdpVoteCount;
	}
}

function ShowHellYa(){
	if(!cdpVoted){
		cdpVoteCount = document.getElementById(targetDivId).innerHTML;
		document.getElementById(targetDivId).innerHTML = "Hell ya";
	}
}

function HideHellYa(){
	if(!cdpVoted){
		document.getElementById(targetDivId).innerHTML = cdpVoteCount;
	}
}

function ShowHellNo(){
	if(!cdpVoted){
		cdpVoteCount = document.getElementById(targetDivId).innerHTML;
		document.getElementById(targetDivId).innerHTML = "Hell no";
	}
}

function HideHellNo(){
	if(!cdpVoted){
		document.getElementById(targetDivId).innerHTML = cdpVoteCount;
	}
}
 
function breakRatingClass(ratingContentId, theName){
	//private vars
	var that = this;
	var voted = false;
	var oldRating;
	
	var myName = theName;
	
	//public vars
	this.contentId = ratingContentId;
	this.isUserLoggedIn = false;
	this.showText = false;
	this.isOwnerWatching = false;
	this.starOutDiv;
	this.messageOutDiv;
	this.thumbDivId = targetDivId;
	this.currentRating;
	this.ratingCallback;
	this.updateRateCallback = "updateRateDisplayCallBack";
	
	this.saveContentRating = function (newRating) {
		voted = true;
		cdpVoted = true;
		try{
			if(cdpVoteCount != undefined){
				document.getElementById(targetDivId).innerHTML = cdpVoteCount;
			}		
		}
		catch(ex){
		}
		var memberId = document.cookie;
		var index = memberId.search (/MemberId=/gi);
		if (index != -1) {
			memberId = memberId.substr (index+9, memberId.length);
			index = memberId.search (/;/gi);
			if (index != -1)
				memberId = memberId.substr (0, index);
			}
			
			var ratingService = new BreakJSON();
			ratingService.sendBegin ("http://websvc.break.com/CMS/handlers/ContentFeedback/ContentFeedbackHandler.ashx?invoke=rate&memberid="+memberId+ "&contentid="+that.contentId+"&vote="+ newRating ,that.ratingCallback);
	}
	
	this.getContentRating = function () {
			var ratingService = new BreakJSON();
			ratingService.sendBegin ("http://websvc.break.com/CMS/handlers/Ratings/ratingsandrecommendationshandler.ashx?invoke=getrate&contentid="+that.contentId ,that.updateRateCallback);
	
	}
}


   
    //Wrapper for recording new rating.
    function rate(newrating) {
 
        if(!ratingObj.isUserLoggedIn && !newCdp)
        {
			GoLogin();
        }
        
        if (!ratingObj.voted)
        {

		    ratingval = newrating;
            ratingObj.saveContentRating(newrating);
            ratingObj.voted = true;            
        }
    } 

    /* var thirdPartyInitRatingMsg = {value: ""}; */
    function publishRatingsCommentsToThirdParty() {
                    
            /* Send ratings comment to 3rd party */
            var thirdPartyName = ThirdPartyMember.getThirdPartyName();
            if (thirdPartyName.toLowerCase() === "facebook") {
                /* do Facebook send */              
                ThirdPartyMember.getName(sendFacebookRatingsComments);
                /*
                //                var templateData = { "video": { "video_src": window.location.href,
                //                "preview_img": getMetaDataByName('embed_video_thumb_url')
                //                    },
                //                    "breakvideourl": window.location.href, "breakvideoname": getMetaDataByName('embed_video_title'), "thumbrating": theRating, "desc": getMetaDataByName('embed_video_description')
                //                };
                //                FB.Connect.showFeedDialog(ThirdPartyMember.ratingTemplateBundleId, templateData, null, "", null, FB.RequireConnect.require, ratingCommentComplete, "Why did you rate this video the way you rated it?", thirdPartyInitRatingMsg);
                */
            }        
    }



    function sendFacebookRatingsComments(result) {
        hideRatingsCommentBox();
        var userInfo = result[0];
        var theRating = (ratingval.toString() === "1") ? "thumbs up" : "thumbs down";
        var comment = document.getElementById("rating_thirdparty_comment").value;
        if (comment === "" || comment === null) {
            comment = (ratingval.toString() === "1") ? "I liked this video" : "I disliked this video";
        }
        var postTitle = getMetaDataByName('embed_video_title') + " video";
        var postCaption = userInfo.first_name + " rated this video " + theRating;

        var attachments = { "name": postTitle, "href": window.location.href, "caption": postCaption, "description": getMetaDataByName('embed_video_description'), "media": [{ "type": "video", "video_src": window.location.href, "preview_img": getMetaDataByName('embed_video_thumb_url'), "video_title": getMetaDataByName('embed_video_title')}]};

        var actionLinks = [{ "text": "Watch Video", "href": window.location.href}];
        //FB.Connect.streamPublish(comment, attachments, actionLinks, null, null, callBack, true);
        mcs.postCommentToThirdParty(postTitle, postCaption, ThirdPartyMember.getThirdPartyName(), comment, window.location.href, getMetaDataByName('embed_video_description'), getMetaDataByName('embed_video_url'), getMetaDataByName('embed_video_thumb_url'), getMetaDataByName('embed_video_title'), thirdPartRatingsCallback);
    }

    function thirdPartRatingsCallback(result) {        
        /* alert(result); */
    }
    
    
    function getMetaDataByName(metaName){
        var metaArray = document.getElementsByName(metaName);
        if (metaArray && metaArray.length > 0){   
             return metaArray[0].content;             
        }
        return null; /* Should never get here */
    }

    function callBack(result) {        
        hideRatingsCommentBox();
    }
    

	function updateRateDisplayCallBack (jsonData) {
		if (jsonData.Response.Code ==0)
		{
            rating = jsonData.Response.Message;
            if (document.getElementById(ratingObj.thumbDivId)){
                document.getElementById(ratingObj.thumbDivId).innerHTML = displayThumbCount(rating);
            }
            /* If this is a facebook user, show the rating box */
            
		}
	}
	
    //Call back for Rating method Use by Static and Dynamic CDP.
    function thumbsRatingCallBack(jsonData){
		if (jsonData.Response.Code ==0)
		{
	        ratingObj.currentRating = parseInt (document.getElementById (ratingObj.thumbDivId).innerHTML);
			if (ratingval > 0)
			{
				rating = parseInt(ratingObj.currentRating) + ratingval  ;
		       
		        if (rating >= 0)
		        {
		            ratingObj.currentRating = rating;
		            document.getElementById (ratingObj.thumbDivId).innerHTML = displayThumbCount(rating);
		        }
			}
			jQuery("#thumbs_container").fadeOut("slow",function() {
			document.getElementById ("thumbs_container").innerHTML = "<span style='font-size:95%;font-weight:bold;color:#336699;'>Thanks</span>";
			jQuery("#thumbs_container").fadeIn("slow");
			});
			
			/*
			$("#thumbs_up").fadeTo("slow",0.50);
			$("#thumbs_down").fadeTo ("slow",0.50);
			$("#thumbs_text").fadeOut("slow",function() {
				document.getElementById ("thumbs_text").innerHTML = "Thanks";
				$("#thumbs_text").fadeIn("slow");
				document.getElementById("thumbs_up").innerHTML = "<img border='0' src='http://media1.break.com/static/live/v1/img/recommendations/rec_thumb_up.gif'/>";
				document.getElementById("thumbs_down").innerHTML = "<img border='0' src='http://media1.break.com/static/live/v1/img/recommendations/rec_thumb_down.gif'/>";
			});
			*/

		}
    }
	

    
	
    function GoLogin(){
        document.location = "http://my.break.com/Member/Authentication/Login.aspx?AppRedirect=" + location.href;
    }

    function displayThumbCount(SS) {
        var T = "", S = String(SS), L = S.length - 1, C, j, P = S.indexOf(".") - 1;
        if (P < 0) {
            P = L;
        }
        for (j = 0; j <= L; j++) {
            T += C = S.charAt(j);
            if (j < P && (P - j) % 3 == 0 && C != "-") {
                T += ",";
            }
        }
        return T;
    }


    function getThirdPartyRatingCommentOverlay() {        
        return ("<style type=\"text\/css\">.fb_header{margin-top:5px;margin-left:19px;float:left;width:260px;color:#336699;font-family:Arial;font-size:14px;font-weight:bold;}.fb_mini_header{font-size:14px;}.fb_close{float:right;width:24px;}.fb_register_msg{clear:both;padding:10px 0px 0px;width:260px;margin-left:17px;} .fb_primary_submit {background-color:#3B5998; margin:5px 0px 0px 5px;border-color:#D9DFEA #0E1F5B #0E1F5B #D9DFEA;border-style:solid;border-width:1px;color:#FFFFFF;font-family:\"lucida grande\",tahoma,verdana,arial,sans-serif;font-size:11px;padding:2px 15px 3px;text-align:center;}.fb_opt_submit {background:#F0F0F0 none repeat scroll 0 0;border-color:#E7E7E7 #666666 #666666 #E7E7E7;color:#000000;}\n\nbody > #fb_rating_box{visibility:hidden;position:absolute;z-index:1000;width:310px;height:200px;border:4px solid #3B5998;}</style><div id=\"fb_rating_box\" style=\"border:4px solid #3B5998;\"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody><tr><td valign=\"top\"><div class=\"fb_header\">Publish this Rating to Facebook!</div><div class=\"fb_close\"><a href=\"javascript:void(0);\" onclick=\"hideRatingsCommentBox();return false;\" class=\"regthis_closebox\"><img alt=\"Close\" src=\"http://media1.break.com/static/live/v1/img/site/regthis/regthis_close.gif\"/></a></div><div class=\"register_msg fb_register_msg\" style=\"\">Why did you rate the video \"thumbs up\"?</div><div style=\"padding:4px 0px 0px 17px;\"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody> <tr><td><textarea id=\"rating_thirdparty_comment\" cols=\"30\" rows=\"6\"></textarea></td></tr><tr><td align=\"right\"><input type=\"button\" value=\"Publish\" onclick=\"publishRatingsCommentsToThirdParty()\" name=\"pub_fb\" id=\"pub_fb\" class=\"fb_primary_submit\" /><input type=\"button\" onclick=\"hideRatingsCommentBox();\" value=\"Skip\" name=\"skip_fb\" id=\"skip_fb\" class=\"fb_primary_submit fb_opt_submit\" /></td></tr></tbody></table></div></td></tr></tbody></table></div>");
    }

    window.mouseClickX = null;
    window.mouseClickY = null;

    function showRatingsCommentBox(result) {
        ThirdPartyMember.showHiddenDiv(); /* show hidden div if necessary */
        if (result !== null) {            
            if (result.toString() === "0" || result.toString() === "false") { return; }
            /* Send ratings comment to 3rd party */
            var thirdPartyName = ThirdPartyMember.getThirdPartyName();
            if (thirdPartyName.toLowerCase() === "facebook") {
                jQuery("body").append(getThirdPartyRatingCommentOverlay());
                jQuery("#fb_rating_box").css("position", "absolute");
                jQuery("#fb_rating_box").css("left", mouseClickX);
                                
                var loc = window.location.href;
                var rbHeight = jQuery("#fb_rating_box").height();
                var boxOnYAxis = (parseInt(mouseClickY) - rbHeight) - 10;
                if (loc.indexOf("/crackle-originals/") != -1 || loc.indexOf("/crackle-minisodes/") != -1){                    
                    boxOnYAxis = parseInt(mouseClickY);
                }                
                
                jQuery("#fb_rating_box").css("top", boxOnYAxis);
                jQuery("#fb_rating_box").css("visibility", "visible");
                jQuery("#fb_rating_box").css("background", "#FFFFFF url('http://media1.break.com/static/live/v1/img/site/regthis/regthis_bg_cnt_tile.png') repeat-x scroll left bottom");
                jQuery("#fb_rating_box").css("padding", "5px 0px 10px 0px");
                
            }
        }
    }

    function hideRatingsCommentBox() {        
        jQuery("#fb_rating_box").css("visibility", "hidden");
    }

    jQuery(document).ready(function() {

        jQuery("#thumb_up").click(function(e) {
            mouseClickX = parseInt(e.pageX) - 5;
            mouseClickY = parseInt(e.pageY);            
            /* Check to see if this is a 3rd party member */
            if (thirdPartyIsLoggedIntoBreak()) {
                /* See if we need to pop up a dialog box for the member to post to the 3rd party site */
                ThirdPartyMember.checkPermissions(showRatingsCommentBox, "publish_stream", "playerwrap");
            }

        });

        jQuery("#thumb_down").click(function(e) {
        mouseClickX = parseInt(e.pageX) - 5;
            mouseClickY = parseInt(e.pageY) + 10;
            /* Check to see if this is a 3rd party member */
            if (thirdPartyIsLoggedIntoBreak()) {
                /* See if we need to pop up a dialog box for the member to post to the 3rd party site */
                ThirdPartyMember.checkPermissions(showRatingsCommentBox, "publish_stream");
            }
        });

    });
