var _member = new Member();
var _cartTabSelected="H";
var _rating=0;        
function closeReview(_clearFields)
{
    $("#writeBox").hide();
    if(_clearFields) {
        $("#reviewTitle").val("Write the title of your review here...");
        $("#reviewDescription").val("Write the review here...");
    }
}
function switchTopRatingCtrl(_rate)
{
    //hide top control
    $("#divTopRateCtrl").hide();
    //show rating image
    $("#divTopRateStars").show();
    $("#imgTopRating").attr("src","../images/ratings/rating_"+_rate+".gif");

}
$('input[@name=star1]').rating({
    callback: function(value){
        _rating = value;
    //switchTopRatingCtrl(value);
    }
});
$('input[@name=star2]').rating({
    callback: function(value){
        
        if($("#mid").length === 0) {
            alert("You must be logged to rate a film. \nPlease click on the login link above.");
            return false;
        }

        //stuff rating
        _rating = value;
        //hide top control
        switchTopRatingCtrl(value);
        //check if there is no member rating
        if($("#reviewId").val() === "" || $("#reviewId").val() === "0") {
            var c = confirm("Thanks for rating!\nSelect \"ok\" to write a review. Select \"cancel\" to skip it.");
            if(c) {
                $('input[@name=star1]').rating('select',_rating)
                $.scrollTo(99999, 1000);
                moveReview('');
            }
            else {
                addReview(true);
            }
        }
        else {
            alert("It appears you have already rated this film.\nIf you wish to change your review, scroll down to the user reviews.");
        }
    }
});


function addReview(_ratingOnly)
{

   var rid="0";
    if($("#reviewId").val() !== "" && $("#reviewId").val() !== "0") {
	rid=$("#reviewId").val();
    }

    if(rid==="0" && !_ratingOnly && ($("#reviewTitle").val()==="" ||
        $("#reviewTitle").val() === "Write the title of your review here...")) {
        alert("Please enter a title for your review.");
        $("#reviewTitle").focus();
        return false;
    }
    if(rid==="0" && !_ratingOnly && ($("#reviewDescription").val()==="" ||
        $("#reviewDescription").val() === "Write the review here...")) {
        alert("Please enter a description for your review.");
        $("#reviewDescription").focus();
        return false;
    }
    if(_rating === 0) {
        alert("Please choose a rating for your review.");
        return false;
    }

    var r = new Object();
    r.memberId = $("#mid").val();
    r.rating = _rating;
    r.filmId = parseInt($("#fid").val());
    r.status = 1;
    if($("#reviewId").val() !== "" && $("#reviewId").val() !== "0") {
        r.reviewId = parseInt($("#reviewId").val());
    }
    else {
        r.reviewId = 0;
    }
    if(_ratingOnly) {
        r.title = '';
        r.description = '';

        //change write box
        $("#reviewTitle").val(r.title);
        $("#reviewDescription").val(r.description);
        $("#btnPostReview").val("EDIT REVIEW");
        $("#divStar1").html("<img src=\"../images/ratings/rating_"+_rating+".gif\" border=\"0\"/>");
    }
    else {
        r.title = $("#reviewTitle").val();
        r.description = $("#reviewDescription").val();
    }
    if($("#reviewDescription").val() === "Write the review here...") {
	r.title = '';
    }
    if($("#reviewTitle").val() === "Write the title of your review here...") {
	r.description = '';
    }

    //edit or add
    if(r.reviewId === 0) {
        reviewDao.insertReview(r, function(data){
            if(data !== null) {
                //apply id
                $("#reviewId").val(data);
                r.reviewId = parseInt(data);
                displayReview(r,true);
                return true;
            }
            else{
                alert("We experienced some problems creating your rating. Perhaps refresh the page and try again.");
                return false;
            }
        });
    }
    else {
        reviewDao.updateReview(r, function(data){
            if(data !== null) {
                //apply id
                displayReview(r,false);
                return true;
            }
            else{
                alert("We experienced some problems creating your rating. Perhaps refresh the page and try again.");
                return false;
            }
        });
    }
    
}
function displayReview(r,_newReview) {
    //display review
    $("#myReview").remove();
    $("#beFirst").remove();
    try{
        var sn = $('a[href*="profile"]').html().substring(6).replace("!","")||"me";
    }
    catch(err){}
//    console.log(_rating);
    var reviewHtml = "<div id=\"myReview\"><div style=\"float:right;margin:0px;\"><div style=\"width:80px;\">"
    +"<img src=\"../images/ratings/rating_"+_rating+".gif\" border=\"0\" /></div></div>"
    +"<p><a href=\"../members/profile?Id="+r.memberId+"\">"
    +"<img align=\"left\" border=\"0\" style=\"margin:5px;\" width=\"87\" height=\"64\" src=\"../content/members/"+r.memberId+".jpg\" /></a>"
    +" <b>"+r.title+"</b>"
    +"<br/> by <a href=\"../members/profile?Id="+r.memberId+"\">"+sn+"</a>"
    +"<br/> "+r.description+"</p></div>";
    $("#reviewBlocks").append(reviewHtml);

    $("#lWriteReview").hide();

    if(_newReview) {
        closeReview(false);
        var _rt = parseInt($("#rateTotal").html().replace("(","").replace(")",""))+1;
        $("#rateTotal").html( "(" +_rt +")" );
        alert("Your rating has been added. Thanks!");

    }
    else {
        closeReview(false);
        $("#editReviewCtrls").show();
        alert("We have updated your rating and review for this film.");
    }

}
function deleteReview(_reviewid) {
    var c = confirm('Are you sure you wish to delete this review?');
    if(c) {
        reviewDao.deleteReview(_reviewid, function(data){
            $("#myReview").remove();
            $("#editReviewCtrls").hide();
            alert("Your review has been deleted.");
        });
    }
    return false;
}

function markOffensive(_reviewId)
{
    var r = new Object();
    r.reviewId = _reviewId;
    r.memberId = $("#mid").val();
    r.offensive = 1;
    
    reviewDao.updateReview(r, function(){
        alert("Thank you for the feedback. We will research this review.");
        closeReview();
    });
}
function rateReview(_goodOrBad, _reviewId)
{
    var r = new Object();
    r.memberId = $("#mid").val();
    r.filmId = $("#fid").val();
    r.reviewRating = _goodOrBad;
    r.reviewId = _reviewId;
    reviewDao.updateReviewRating(r, function(data){
        if(data>0){
            alert("Thank you for reviewing this rating.");
            var _rr=parseInt($("#reviewRating-"+_reviewId).html())+_goodOrBad;
            var _rrt=parseInt($("#reviewRatingTotal-"+_reviewId).html())+1;

            if(_rr=="")
                _rr=0;
            $("#reviewRating-"+_reviewId).html("").html(_rr);
            $("#reviewRatingTotal-"+_reviewId).html("").html(_rrt);
        }
        else
            alert("It seems you might of already rated this film.");
    });
}
function visitCart()
{
    var c = $.cookieJar('reframeCart');
    var _id = c.get('cartId');
    var _h = escape(c.get('hmac')).replace(/\//g,'%2F').replace(/\+/g,'%2B').replace(/\=/g,'%3D');
    document.location.href = "../cart/index?Id="+_id+"&h="+_h;
}
function createAmazonCart(asin, filmTitle)
{
    cartDao.makeCart(asin, function(_cart){

        //getMember();
        try{
            if(_member != null && _member.memberId>0)
            {
                _member.cartId = _cart.cartId;
                _member.hmac = _cart.hmac;
                memberDao.updateMember(_member, function(){});
            }
        }catch(err){}
                        
        var c = $.cookieJar('reframeCart');
        c.set('cartId', _cart.cartId);
        c.set('hmac', _cart.hmac);

        $.cookie('reframe_cart', _cart.cartId);
        $.cookie('reframe_hmac', _cart.hmac);
                                
        if(_cart.cartId!='')
        {
            $("#cartStatus").html("<b>"+filmTitle+"</b> has been added to your cart. <a href='../cart/index?Id="+_cart.cartId+"&h="
                +_cart.hmac.replace(/\//g,'%2F').replace(/\+/g,'%2B').replace(/\=/g,'%3D')+"'>Click here</a> to view your cart.").fadeIn("fast");
            checkCartStatus();
            $("#td-"+asin).html("").html("Added to Cart");
        }
        else
        {
            $("#cartStatus").html("<b>"+filmTitle+"</b> is already in your cart. <a href='../cart/index?Id="+_cart.cartId+"&h="+_cart.hmac+"'>Click here</a> to view your cart.").fadeIn("fast");
            $("#td-"+asin).html("");  
        }
    });
}
                        
                        
                        


function checkIt(_box)
{
    if(_box==='t')
    {
        if($("#title").val()==="Write your list title here (REQUIRED)")
            $("#title").val("");
    }
    else if(_box==='d')
    {
        if($("#description").val()==="Describe your list here...")
            $("#description").val("");
    }
    else if(_box==='rt')
    {
        if($("#reviewTitle").val()==="Write the title of your review here...")
            $("#reviewTitle").val("");
    }
    else if(_box==="rd")
    {
        if($("#reviewDescription").val()==="Write the review here...")
            $("#reviewDescription").val("");
    }
}

function getMember()
{
    memberDao.getAuthenticatedMember( function(m){
        if (m != null && typeof m == 'object') 
            _member = m;
    });   
}

function jumpToCuratedList()
{
    if($(this).children("[@selected]").val() != null)
        document.location.href = '../curatedLists/curatedList?Id='+$(this).children("[@selected]").val();
    else
        document.location.href = '../members/lists?Id='+ $("#mid").val();
}
function removeFilmfromList()
{
    var _filmid = $("#fid").val();
    var _cid = $("#curatedLists").children("[@selected]").val();
    var text = $("#curatedLists").children("[@selected]").text();
                
    curatedListDao.deleteFilmfromCuratedList(_cid, _filmid,0, function(data){
        $("#listStatus").html("").html("This film was removed from:<br/><div style='font-size:1.25em;font-weight:bold;text-decoration:underline;'>"+text+"</div>").fadeIn();
    });
}
function moveLearn()
{
    $("#h3Synopsis").addClass("expando-open");
    $("#h3Synopsis + div.expando-wrap").addClass("expando-open").css('display','block');

    $("#h3Cast").addClass("expando-open");
    $("#h3Cast + div.expando-wrap").addClass("expando-open").css('display','block');

    $("#h3Credits").addClass("expando-open");
    $("#h3Credits + div.expando-wrap").addClass("expando-open").css('display','block');
    
    $("#h3Awards").addClass("expando-open");
    $("#h3Awards + div.expando-wrap").addClass("expando-open").css('display','block');
    
    $("#h3Genres").addClass("expando-open");
    $("#h3Genres + div.expando-wrap").addClass("expando-open").css('display','block');
    
    $("#h3Subjects").addClass("expando-open");
    $("#h3Subjects + div.expando-wrap").addClass("expando-open").css('display','block');
}
function moveList()
{
    $("#h3AddToList").addClass("expando-open");
    $("#h3AddToList + div.expando-wrap").addClass("expando-open").css('display','block');
}
function moveReview(_showForm)
{
    $("#h3UserReview").addClass("expando-open");
    $("#h3UserReview + div.expando-wrap").addClass("expando-open").css('display','block');

    if(_showForm=='')
        $('#writeBox').show();
}
function addNewCuratedList() {
    
    var msg="";
    
    if(msg.length==0 && $("#title").val()<5)
        msg = "Please enter a title for your curated list.";
    if($("#mid").val() == null || $("#mid").val() == 0)
        document.location.href = "../login/";
    
    if(msg.length>0)
    {
        $("#listStatus").html("").html(msg).fadeIn();
        return false;
    }
    else
    {
        var cl = {
            title: $("#title").val(),
            description: $("#description").val(), 
            status: 1, 
            memberId: $("#mid").val()
        };
           
        curatedListDao.insertCuratedList(cl, function(_curatedlistid){
            $("#listStatus").fadeOut("fast");
            if(_curatedlistid>0){
                $("#curatedLists").addOption(_curatedlistid, $("#title").val());
                                                                   
                curatedListDao.addFilmtoList(_curatedlistid, $("#fid").val(), function(data){ 
                    $("#listStatus").html("").html("This film was added to:<br/><div style='font-size:1.25em;font-weight:bold;text-decoration:underline;'>"+$("#title").val()+"<br/><a href='javascript://' onClick='removeFilmfromList();' style='font-size:.7em;text-decoration:none;color:#666;'>remove film</a><br/><a href='javascript://' onclick='jumpToCuratedList();' style='font-size:.9em;font-weight:normal;text-decoration:underline;'>Add more films to this list</a></div>").fadeIn();
                });
                $("#btnCreate").val("CREATE LIST & ADD FILM");
            }
            else
                $("#listStatus").html("").html($("#title").val()+" has not been added.").fadeIn();
        });
        return true;
    }
}


var debugging = true; // or true
if (typeof console == "undefined") var console = { log: function() {} };
else if (!debugging || typeof console.log == "undefined") console.log = function() {};
//*********
//subjects
var subParents=[];
var subChildren=[];
var subSubjects=[];
function Sub(_subjectId, _parentId, _title, _indent, _added)
{
    this.subjectId = _subjectId;
    this.parentId = _parentId;
    this.title = _title;
    this.indent = _indent?_indent:"0";
    this.added= _added;
}
function splitUpParentsChildren() {

	$.each($("#h3Subjects+div>p>a"), function(){
		var _pid = $(this).attr("pid")?$(this).attr("pid"):0;
		var _sid = $(this).attr("sid")?$(this).attr("sid"):0;
		var indent="0";
                if(_pid>0)
                    indent="1";
                else
                    indent="0";
                var _title = $(this).attr("title")?$(this).attr("title"):"";
                var sub = new Sub(_sid, _pid, $(this).attr("title") , indent, false);
                subParents.push(sub);
	});
	loopThruChildren();
}
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
function getTheChildren(_parents, _children) {

    $.each(_parents, function(_index, _parentValue) {
        $.each(_children, function(_childIndex, _childValue){
            if(_childValue.parentId > 0) {
                if(_childValue.parentId == _parentValue.subjectId) {
                    var s = new Sub(_childValue.subjectId, _childValue.parentId, _childValue.title, 1, true);
                    subSubjects.push(s);
                }
            }
        });
    });
}
function loopThruChildren(){

        var parentsToRemove=[];
        var tempArray=[];
        var subSubjects=[];
        console.log("start length:"+subParents.length);
        //grab all root parents
	$.each(subParents, function(parentIndex, parentValue){
            if(parentValue.parentId=="0"){
		subSubjects.push(parentValue);
                parentsToRemove.push(parentIndex);
            }
	});

        //remove added subjects
        $.each(parentsToRemove, function(index, value){
              subParents.remove(value);
	});
        parentsToRemove=[];

        //find all 2nd level children
        tempArray=subSubjects;
        $.each(subSubjects, function(i, v){
            $.each(subParents, function(childIndex, childValue) {
                if(typeof childValue != "undefined"){
                    if(childValue.parentId != "0" && (childValue.parentId == v.subjectId && childValue.subjectId != v.subjectId)) {
                        tempArray.push(new Sub(childValue.subjectId, childValue.parentId, childValue.title, 1, true));
                        parentsToRemove.push(childIndex);
                    }
                }
            });
        });
        subSubjects=tempArray;

        //remove added subjects
        $.each(parentsToRemove, function(index, value){
              subParents.remove(value);
	});
        tempArray=parentsToRemove=[];


        //find all 3rd level children
        tempArray=subSubjects;
        $.each(subSubjects, function(i, v){
            $.each(subParents, function(childIndex, childValue) {
                if(typeof childValue != "undefined" && (childValue.parentId == v.subjectId && childValue.subjectId != v.subjectId)) {
                    tempArray.push(new Sub(childValue.subjectId, childValue.parentId, childValue.title, 1, true));
                    parentsToRemove.push(childIndex);
                }
            });
        });
        subSubjects=tempArray;

        //remove added subjects
        $.each(parentsToRemove, function(index, value){
              subParents.remove(value);
	});
        tempArray=parentsToRemove=[];


        //find all 3rd level children 2 time
        /*
        tempArray=subSubjects;
        $.each(subSubjects, function(i, v){
            $.each(subParents, function(childIndex, childValue) {
                if(typeof childValue != "undefined" && (childValue.parentId == v.subjectId && childValue.subjectId != v.subjectId)) {
                    tempArray.push(new Sub(childValue.subjectId, childValue.parentId, childValue.title, 1, true));
                    parentsToRemove.push(childIndex);
                }
            });
        });
        subSubjects=tempArray;
        
        //remove added subjects
        $.each(parentsToRemove, function(index, value){
              subParents.remove(value);
	});
        tempArray=parentsToRemove=[];
        */

        

        console.log(subParents.length+" "+subSubjects.length);
         $.each(subSubjects, function(index){
              console.log(subSubjects[index]);
	});


/*


	var _children=[];
	$.each(subChildren, function(childIndex, childValue){
		$.each(subSubjects, function(sIndex, sValue){
			if(sValue.subjectId == childValue.subjectId){
				_children.push(childIndex);
			}
		})
	});
	$.each(_children, function(_index, _value){
	    subChildren.remove(_value);
	});
	var _subjects=[];
	$.each(subSubjects, function(parentIndex, pv){
		_subjects.push(pv);
		$.each(subChildren, function(childIndex, cv) {
			if(//cv != undefined && pv != undefined && cv.parentId != undefined && pv.subjectId != undefined &&
                            cv.parentId == pv.subjectId) {
				var s = new Sub(cv.subjectId, cv.parentId, cv.title, 2, true);
				_subjects.push(s);
                console.log(s);
				return;
			}
		});
	});
var _removeSubjects=[];
var _SubjectTitle="";
$.each(_subjects, function(index, subject){
if(_SubjectTitle==subject.title){
_removeSubjects.push(index);    
}
_title=subject.title;
});
$.each(_removeSubjects, function(_i, _v){
    _subjects.remove(_v);
});
*/
//writeHtml(_subjects);
}
function writeHtml(_subjects) {
	var subjectHtml="<div>";
	var i=0;
	$.each(_subjects, function(_index, _value){

	var leftPadding=0;
	var titleStyle="normal";

	if(this.indent===0) {
		leftPadding=0;
		titleStyle="bold";
	} else if(this.indent===1) {
		leftPadding=15;
		titleStyle="normal";
	} else if(this.indent===2) {
		leftPadding=30;
		titleStyle="normal";
	}

	var _s=this;
	subjectHtml+="<span style=\"font-weight:"+titleStyle+";\">";
        if(_s.parentId==0 && i>0)
          subjectHtml+="<br/>";
	if(_s.parentId>0)
	  subjectHtml+=" >";
	subjectHtml+=" <a href=\"../subjects/subject?Id="+_s.subjectId+"\">"+_s.title+"</a>";
	subjectHtml+="</span>";
	i++;
	});

	subjectHtml+="</div>";
	if(subjectHtml.length>1){
		$("#h3Subjects+div>p").html("").html(subjectHtml);
	}
}

//DOCUMENT READY
$(document).ready(function() {


    getMember();

    $("#writeBox>div>div>ul>li>a>img").mouseover(function(){
        if($(this).attr("src").indexOf('blank')>0)
        {
            $(this).attr("src","../images/star.gif");
        }
        else
        {
            $(this).attr("src","../images/star_blank.gif");
        }
    });

    $("#closeReview").click(function(){
        closeReview();
    });
    $("#btnPostReview").click(function(){
        addReview(false);
        
    });
    $(".divRateReviews>a").click(function(){
        var _goodOrBad = 0;

        if($(this).html()=="YES")
            _goodOrBad = 1;

        var _reviewid = parseInt($(this).attr("id").substring(1));

        $(".divRateReviews>a").css("color","#ccc").css("text-decoration","underline").css("font-weight","normal");
      
        rateReview(_goodOrBad, _reviewid );
    });

    $("#cartTabs>li>a").click(function(){
                            
        $.each($("#cartTabs>li>a"), function(){
            $(this).css("color","#999").css("text-decoration","underline"); 
        });
                            
        $(this).css("color","#000").css("text-decoration","none");
                            
        var _id = $(this).attr("id").replace("sku","tab");
                            
        $("#tab-"+_cartTabSelected).fadeOut("normal", function(){
            $("#"+_id).fadeIn();
        });
                            
        _cartTabSelected = _id.substring(4);
    });
    
    
    $(".reframeForm").validate({
        rules: {
            title: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            title: "<span style='color:maroon'><br/>Title for your list must be over five characters.</span>"
        }
    });
    $("#curatedLists").change(function(){
        if($(this).children("[@selected]").val().length>0)
        {
            var _filmid = $("#fid").val();
            var cid = $(this).children("[@selected]").val();
            var text = $(this).children("[@selected]").text();
            curatedListDao.addFilmtoList(cid, _filmid, function(data){
                if(data>0)
                    $("#listStatus").html("").html("This film was added to:<br/><div style='font-size:1.25em;font-weight:bold;text-decoration:underline;'>"+text+"<br/><a href='javascript://' onClick='removeFilmfromList();' style='font-size:.7em;text-decoration:none;color:#666;'>remove film</a></div>").fadeIn();
                else
                    $("#listStatus").html("").html("This film already exists in:<br/><div style='font-size:1.25em;font-weight:bold;text-decoration:underline;'>"+text+"<br/><a href='javascript://' onClick='removeFilmfromList();' style='font-size:.7em;text-decoration:none;color:#666;'>remove film</a></div>").fadeIn();
                             
            });
        }
    });
                    
                    
    $(".atc").click(function(){
                            
        var _asin = $(this).attr("id").substring(9);
        var _title = $("#filmTitle").val();
        var c = $.cookieJar('reframeCart');
                                
        if (c.get('cartId') != undefined)
        {
            $("#td-"+_asin).html("").html("<i>Adding to Cart...</i>");
            cartDao.addToCart(c.get('cartId'), c.get('hmac'), _asin, function(success){
                if(success){
                    $("#cartStatus").html("<b>"+_title+"</b> has been added to your cart. <a href='javascript://' onClick='visitCart();'>Click here</a> to view your cart.").fadeIn();
                    checkCartStatus();
                    $("#td-"+_asin).html("").html("Added to Cart");
                }
                else
                {
                    $("#cartStatus").html("<b>"+_title+"</b> is already in your cart. <a href='javascript://' onclick='visitCart();'>Click here</a> to view your cart.").fadeIn();
                    $("#td-"+_asin).html("");   
                }
            });
                                    
            //m is logged in so update w/ cart
            if(_member.memberId != '')
            {
                if(c.get("mid")==undefined)
                {
                    _member.cartId = c.get('cartId');
                    _member.hmac = c.get('hmac');
                                     
                    memberDao.updateMember(_member, function(){
                        var c = $.cookieJar('reframeCart');
                        c.set('mid', _member.memberId);
                    });
                }
            }
        }
        //nothing so create cart
        else
        {
            $("#td-"+_asin).html("").html("<i>Adding to Cart...</i>");
            createAmazonCart(_asin, _title);
        }
    });
                         
                    
});
