/*-------------------- Dynamicbox Determiner --------------------*/

//path used on the main menu to sign out
var signoutPath = "";

function loggedInAndHasReview() {        
    //return loggedIn;
     return ($("#quickRate input").is(":checked"));
}

// is anything in the quickRate app checked?
function hasRating() {    
    if ($("#quickRate input").is(":checked")) {  // || $(".your-rating input").is(":checked")        
        return true; }
    else {         
        return false; }
}

// determine what to show in the #dynamic_action area
function toggleDynamicArea() {
    if (loggedInAndHasReview()) {
        if (hasRating()) { 
            $(".hasNotRated").hide();            
            $(".hasRated").show(); 
        }
        else { 
            $(".hasNotRated").show(); }        
    } 
    else {        
        $(".hasNotRated").show(); }
}

/* find the anchor */
function getPopupAnchor() {
    var thisEl;
    
    if ($("div.hasNotRated").css("display") == "block") {
        thisEl = $("div.hasNotRated a img");
    } else if ($("div.hasRated").css("display") == "block") {
        thisEl = $("div.hasRated ul li a#lastRating");
    }
    return thisEl;
}

/* dynamically position the layer depending on location */
function positionQuickRateLayer() {        		
	if ($(".hasNotRated").is(":visible")) {
		var thisEl = $("div#dynamic_action .hasNotRated a");
	} else if ($(".hasRated").is(":visible")) {		
    	var thisEl = $("div#dynamic_action .hasRated #rating_action");    
	} else {
		thisEl = $("div#dynamic_action");	// just in case
	}
	
    // get the element coordinates
    var coords = $(thisEl).offset();
        
    // get parent container coordinates
    var parentContainer = $("#quickrate_popup_layer").parents("#main").offset();
    
    // determine pop-up layer size
    var boxWidth = parseInt($("#quickrate_popup_layer").css("width"));
    var boxHeight = parseInt($("#quickrate_popup_layer").css("height"));   
        
    // determine anchor relative to edge of page container
    var linkDifference = Math.abs($("#container").offset().left-$(thisEl).offset().left);
            
    // get anchor point dimensions    
    var anchorWidth = $(thisEl).innerWidth();   
    var anchorHeight = $(thisEl).height();
    
    var posLeft = 0; 
    var posTop = 0;  
    var arrowOffset = 16;
    var vOffset = 0;
    
    // used to account for different readings of height
    if (anchorHeight = 24) {
        vOffset = -7;
    } else if (anchorHeight = 40) {
        vOffset = 13;
    }
    
    // determine how the box should be rendered - left or right side    
    if (linkDifference < boxWidth) {
        // put on right side
        if (!($("#quickrate_popup_layer div.arrow_left").size() > 0)) {
            $("#quickrate_popup_layer").append("<div class='arrow_left'></div>");        
        }        
        
        posLeft = coords.left - parentContainer.left + anchorWidth + arrowOffset + 10; 
        posTop = coords.top -(parentContainer.top) ;
        
        // display the box
        $("#quickrate_popup_layer").css("left", posLeft).css("top", posTop);
    } else {
        // put on the left side
        if (!($("#quickrate_popup_layer div.arrow").size() > 0)) {
            $("#quickrate_popup_layer").append("<div class='arrow'></div>");                
        }        
        
        posLeft = coords.left - parentContainer.left -boxWidth - arrowOffset - 0; //22;
        posTop = coords.top - parentContainer.top;
        // display the box
        $("#quickrate_popup_layer").css("left", posLeft).css("top", posTop);
    }    
}



// catch clicks only on the quickrate popup layer
// WSS event
$(document).ready(function() {
	// move quickRate is on fanreview page since it's offset in a different location
	if ($("#quickrate_popup_layer").parent().attr("id") == "writereview") {
		$("#quickrate_popup_layer").appendTo($("#main"));
	}

	// determine what to show in the #dynamic_action area
    toggleDynamicArea();     

	// continuously position the quickRateLayer
	$(".rating-app").livequery(function() {
	    positionQuickRateLayer();
	});    
	
	$("#login_form li:last a.textLink").click();
       
    // Catch click for the Read All Reviews Link
	// WSS event
    $("#meter a.action").click(function() {
        var lid = "Urev_Box_Read_All";
        _hbLink(lid, lid);           
        return false;   
    });
    
    // hover function
    var layerTimer; 
    $("#quickrate_popup_layer").hover(function() { 
        clearTimeout(layerTimer);       
        $("#quickrate_popup_layer").show(); 
    }, function() {
        //layerTimer = setTimeout("$('#quickrate_popup_layer').hide()",1000);
    });



	// trigger for mouseover rate this movie
    $("#dynamic_action .quickRateImg").click(function(e) {             
       var quickRate = document.getElementById("quickRate");
              
       if (quickRate != null) {           
             positionQuickRateLayer();
            $("#quickrate_popup_layer").show();
       }
       else {
            positionQuickRateLayer();
            ShowSignInLayer(false);             
       }       
    });    
    
    // handles the clicks to the fan reviews
    $(".your-rating ol").click(ratingHandler).find("li");

	// initializes the styling of the radio boxes
    InitializeRadioBoxes("Buzz");  
    InitializeRadioBoxes("Rating");      
    
    // trigger for edit movie rating
	// WSS event
    $("#dynamic_action a.quickRateText").click(function() {
        var lid = "Urev_Box_Edit";
        _hbLink(lid, lid);
        positionQuickRateLayer();        
        $("#quickrate_popup_layer").show();  
    });

    $("#quickrate_popup_layer").bind('click', function(ev) {            
        if ($(ev.target).is('.rating-app') || $(ev.target).parents('.rating-app').length) {            
            
            switch(ev.target.className) {
            case "close":
                CloseLoginPopup();
                break;
            case "continue":
                // if community username link, update url to include the return url. slashes are encoded to avoid url rewriting.
                if($(ev.target).attr("name") == "NoCommunityUsernameLink")
                {
					$(ev.target).attr({ href: $(ev.target).attr("href") + "?s=" + escape(location.toString()).replace(/\//g, "%2F")});
					return true;
                    break;
                }
				
                //handle the continue button on the forgot password box
                if($(ev.target).attr("name") == "ForgetPasswordSubmitLink")
                {
                    var lid = "Urev_Box_Forgot_PW_Email_RO";
                    _hbLink(lid, lid);
                    
                    disableElements(this, ev.target.className); //please wait button
                    ForgotPasswordSubmit($(ev.target));
                }
                else
                {
                    if($(ev.target).attr("name") == "ForgetPasswordEmailSent") 
                    {
                        var lid = "Urev_Box_PW_Emailed_RO";
                        _hbLink(lid, lid);
                    }
                    if($(ev.target).attr("name") == "FailedLogin") 
                    {
                        var lid = "Urev_Box_Not_Match_RO";
                        _hbLink(lid, lid);
                    }
                    
                    //any other continue just brings back the login gui
                    OpenLoginPopup();
                }
                
                ev.preventDefault(); //prevent the page from jumping
                return false;
                break;
            case "signin":
                var lid = "Urev_Box_Sign_In_RO";
                _hbLink(lid, lid);
                
                disableElements(this, ev.target.className); //please wait button
            	LoginPopupSubmit(ev.target);
                //include the signout path so the updated menu knows what the signout link should be (if login is successful)                
                //signoutPath = document.form1.SignoutPath.value; 
                //LoginPopupSignIn(document.form1.email.value, document.form1.password.value, signoutPath, $(ev.target).attr("ajaxhref"), ProcessLoginResults);                
                return false;
                break;
            case "textLink":
                // call a function and do something
                if($(ev.target).attr("name") == "ForgotPasswordLink") 
                {
                    var lid = "Urev_Box_Forgot_PW_RO";
                    _hbLink(lid, lid);
                }
                
                                
                return false;
                break;
            default:                                
                if ($(ev.target).parent().is('span.BuzzStyled') || $(ev.target).parent().is('span.RatingStyled')) {
                    switchRating(ratingHandler(ev));
                    toggleDynamicArea();
                    setTimeout("$('#quickrate_popup_layer').hide()",1000);
                    
                    var lid = "Urev_Box_Rate_RO";
                    _hbLink(lid, lid);
                }
                break;
            }         
        } else {            
            CloseLoginPopup(); // hides the layer when you click anywhere but the rating-app or children elements
        }
    });
});    

// switch the information in the box
function switchRating(eventTarget) {
    var selectedRating = eventTarget.className;    
    $(".hasRated a#lastRating").attr("class",selectedRating);
    if (document.getElementById("hasRatedTitle")) {
        if ($(eventTarget).attr("name") == "Rating") {            
            $("#hasRatedTitle").html("My rating:");   
            $(".hasRated #layout").attr("class","rating");
            $("#WriteReviewLink").text($("input[name='WriteReviewLinkText']").val());            
        } else {
            $("#hasRatedTitle").html("My buzz:");
            $(".hasRated #layout").attr("class","buzz");            
            $("#WriteReviewLink").text($("input[name='WriteReviewLinkText']").val());   
        }
    } else {
        if ($(eventTarget).attr("name") == "Rating") {        
            $(".hasRated li:first").html("My rating:");
        } else {
            $(".hasRated li:first").html("My buzz:");
        }
    }
}

/*-------------------- Quickrate Rating App --------------------*/

// handles the clicks on the ratings
function ratingHandler(ev) {     
    ev.preventDefault(); // prevents the anchor # from page jumping    
    var targetParent = $(ev.target).parent();         
    var selectedBubble = targetParent.children();                                 
                    
    if ($(selectedBubble[1]).attr("name") == "Rating") {
        muteRadioGroup("Buzz"); 
        uncheckRadioGroup("Buzz"); 
        } 
    else {
        muteRadioGroup("Rating");
        uncheckRadioGroup("Rating"); 
        }
   
   var quickRateRequestPath = ($(selectedBubble[0])).attr("ajaxhref");        
   
   if (quickRateRequestPath != null && quickRateRequestPath != "")
   {
        //quick rate...handle the submit instanly
        new AjaxRequest(quickRateRequestPath, null, toggleRadiobox(ev.target,ev.keycode,$(selectedBubble[1]).attr("name"),$(selectedBubble[0]).attr("id"))).run();  
   }
   else
   { 
        //not quick rate...just toggle the graphic
        toggleRadiobox(ev.target,ev.keycode,$(selectedBubble[1]).attr("name"),$(selectedBubble[0]).attr("id")); 
   }
      
    return ev.target;  
}



/*-------------------- Radio Boxes Functions --------------------*/

function InitializeRadioBoxes(radioGroup) {
    var rbGroup = $("span."+radioGroup+"Styled").get();
    var rbGroupInput = "span."+radioGroup+"Styled input";
    var rbGroupA = "span."+radioGroup+"Styled a";
        
    $(rbGroupInput).each(function(i) {
        this.id="StyledRadiobox"+i;
    });
    
    $(rbGroupA).each(function(j) {  
        var spanName = $(rbGroup[j]).attr("name");
         
        if ($(rbGroupInput)[j].checked) {            
            this.className="RadioboxChecked"+spanName;              
            switchRating(this);          
        } else {
            this.className="Radiobox"+spanName;
        }
        $(this).attr("href","#");
    });                
}

/*
	toggleRadiobox(rbObj.rbKey.rbGroup,rbId)
	- this function toggles the state of the button
*/
function toggleRadiobox(rbObj,rbKey,rbGroup,rbId)	{
   	if (rbKey&&rbKey==0||!rbKey) {
		var inputFields = document.getElementsByTagName("a");
		for (var inputIndex=0;inputIndex<inputFields.length;inputIndex++)	{
			if (inputFields[inputIndex].getAttribute("name")==rbGroup) {
				if (inputFields[inputIndex].className.indexOf("RadioboxChecked")<0) {
					var RadioBoxType = inputFields[inputIndex].className.replace("Radiobox","");               
				} else {
					var RadioBoxType = inputFields[inputIndex].className.replace("RadioboxChecked","");
				}
				inputFields[inputIndex].className="Radiobox"+RadioBoxType;
			}
		}
		
		var inputFields = document.getElementsByTagName("input");
		for (var inputIndex=0;inputIndex<inputFields.length;inputIndex++)	{
			if (inputFields[inputIndex].getAttribute("name")==rbGroup) {
				if (inputFields[inputIndex].getAttribute("id")==rbId) {
					if (rbObj.className.indexOf("RadioboxChecked")<0) {
						var RadioBoxType = rbObj.className.replace("Radiobox","");
					} else	{
						var RadioBoxType = rbObj.className.replace("RadioboxChecked","");
                    }
					inputFields[inputIndex].checked = true;
					rbObj.className="RadioboxChecked"+RadioBoxType;
				} else {
					inputFields[inputIndex].checked = false;
				}
			}
		}
	}
}
	
/*
	muteRadioGroup(radioButtonOrGroup)
	- this function changes the visual radio buttons to the off state.
*/	
function muteRadioGroup(radioButtonOrGroup) {   
	var inputFields = document.getElementsByTagName("span"); 
	var radioboxIndex = 0;
	
	for (var inputIndex=0;inputIndex<inputFields.length;inputIndex++) {  
		if (inputFields[inputIndex].className==radioButtonOrGroup+'Styled') { 
			var styleType = "";	styleType = inputFields[inputIndex].getAttribute("name"); 
			
			var lookingFor = ".RadioboxChecked"+styleType;	
			var changeTo = "Radiobox"+styleType;	
			var theClass = $(lookingFor).get();         
         
			for (var i=0;i<theClass.length;i++) {
				theClass[i].setAttribute("class",changeTo);
				theClass[i].setAttribute("className",changeTo); // for IE bug not supporting setAttribute on class
			}
		}
	}
}

/*
	uncheckRadioGroup(radioButtonOrGroup)
	- this function changes the visual radio buttons to the off state.
*/
function uncheckRadioGroup(radioButtonOrGroup) {
    $("input[name='"+radioButtonOrGroup+"']").each(function(i) {
        this.checked = false;                
    });
}
    

/*
   getCheckedValue(radioObj)
   - just for debugging to make sure input boxes were being checked
*/
function getCheckedValue(radioObj) {
    if(!radioObj)
	    return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
	    if(radioObj.checked) {
		    return radioObj.value;         
	    } else 
		    return "";
    for(var i = 0; i < radioLength; i++) {
	    if(radioObj[i].checked) {
		    return radioObj[i].value;
	    }
    }
    return "";
}

//added by brett

function ProcessLoginResults(sender, statusCode, rawResponse)
{  
    if (GetLoginStatusFromResponse(rawResponse))
    {
        //login successful!        
        loggedIn = true;
        //console.log(sender);
        positionQuickRateLayer();
        //load the logged in menus
        //ReloadMainMenu(signoutPath);        
        
        //set the quick rate popup to the logged in state (ajax call)               
        var quickRatePopupRequestPath = document.form1.QuickRatePopupRequestPath.value;
        ajaxRequest = new AjaxRequest(quickRatePopupRequestPath, null, RenderQuickRatePopupFromAjax).run();
        
        //load the logged in menus..they will have been included in the response if it was successful
        UpdateMenu(rawResponse);
    }
    else
    {
        //login failed...write the rawResponse to the popup...it will include the error message
        $(".login_popup_container").html(rawResponse);
    }
}

function RenderQuickRatePopupFromAjax(sender, statusCode, rawResponse)
{  
    $("#quickrate_popup_layer").html(rawResponse);
    InitializeRadioBoxes("Rating");
    InitializeRadioBoxes("Buzz");
    toggleDynamicArea();
    $(".rating-app").show();      
}

function ShowSignInLayer(forceDisplay)
{
    //call the login popup display function
    ShowSignIn("login_popup_container", forceDisplay);
}


