var showPanel;
x= $(document).ready(function() {
 function normalizeErrors(errors){
     
     var res = {};
     var key;
     for ( key in errors){
         res[key] = errors[key].join ? errors[key].join(",") : errors[key];
     }
     return res;
 }
 
 function dump(obj, obj_name){
     log(obj_name);
     var prop;
     for (prop in obj){
         log("\t" + prop + ': ' + obj[prop]);
     }
 }
 
 function log(){
     try{
         if (console && console.log){
             //console.log.apply(null, arguments);
         }
     }catch(err){
         
     }
     
 }
 // =========================
 // = USER MANAGEMENT FORMS =
 // =========================
    // Login form validation and ajax handling
    $("#login-form").validate({
     "rules": {
         "password": {
             "required": true,
             "minlength": 3
         },
         "email": {
             "required": true,
             "email": true
         }
     },
     "messages": {
         "password": {
             "required": "Please provide a password",
             "minlength": "Your password must be at least 3 characters long"
         },
         "email": "Please enter a valid email address"
     },
     "submitHandler": function(theForm){
         $(".submit", $("#login-form")).attr("disabled", true);
         sendLogin(theForm);
         return false;
     }
 });
 
 
 function sendLogin(theForm){
     
     $.post(
         $(theForm).attr("action"),
         {
             "email": $(theForm.email).val(),
             "password": $(theForm.password).val()
         },
         onLoginResponse,
         "json");
 }
 
 function onLoginResponse(data){
     
        $(".submit", $("#login-form")).attr("disabled", false);
     if(data.status=="error" || data.status==null){
         $("#login-form").validate().showErrors({"email":data.errors});
         $(".logged-welcome").addClass("invisible");
     }else{
         updateQuickOrderInfo(data);
         showLoginInfo(true, data.full_name, data);
         loadFavSets();
         $("#account-con").hide();
         $("#favorites-con").show();
         movePanel(true, $("#favorites-con"));
     
     }
 }
 
 function doDeleteFavoriteSet(){
     var setID = getSelectedSetID();
     $.post("/users/json/product-set/" + setID + "/delete/",
         {},
         onFavoriteSetDeleteLoaded,
         "json"
         );
 }
 
 function createNewFavSet(){
     $.post("/users/json/product-set/new/", {}, onCreateNewFavSetLoaded, "json");
 }
 
 function onCreateNewFavSetLoaded(data){
     var success = (data.status=="ok");
     if(success){
         var newNode = createFavSetMenuItemNode(data.name, data.id, 0);
         $("#create-user-favorites").after(newNode);
         markFavSetMenuItem(data.id, true);
         $("ul", $("#fav-set-text")).addClass("invisible");
         $(".thumbnail-con").children().remove();
     }
 }
 function onFavoriteSetDeleteLoaded(data){
     if(data.status=="ok"){
         var menuItemNode = $(".set_id_" + data.deleted.id).parent();
         
         menuItemNode.remove();
         // now we need to select thenext one:
         var newSetEl = getFavMenuItems();
         var newSetID = parseInt($("div",newSetEl).html());
         //$(".fav_set_menu", ".fav_set_menu").remove();
         loadUserFavoritesItems(newSetID, "favorites");
         markFavSetMenuItem(newSetID, true);
     }else{
            $(".delete-error-status").html(data.error);
     }
 }
 
 function doRenameFavoriteSet (setID) {
    var new_name = $("#favset-new-name-input").val();
    if(new_name && new_name.length >1){
           $("#panel-rename-view div.msg").html("Renaming set");
        $.post(
          "/users/json/favorites/" + setID + "/rename/",
          {"new_name":new_name},
          onRenameFavoritesLoaded,
          "json"  
        );
    }else{
        $(".rename-error-status").html("Please enter a new name for your set.");
    }
 }
 
 function onRenameFavoritesLoaded(data){
     if (data.status == "ok"){
         // change the menu item
            var newMenuNode = createFavSetMenuItemNode(data.name,data.id, data.items ? data.items.length:0);
            
            var baseNode = $(".set_id_" + data.id).parent();
            baseNode.after(newMenuNode);
            baseNode.remove();
         // change rename set form
         markFavSetMenuItem(parseInt(data.id), true);

         // display message
         // change message:
         $(".rename-error-status").html("Set renamed successfully.");
         
     }else{
         $(".rename-error-status").html("Oops, could not rename your favorite set.");
     }
 }
 
 function createFavSetMenuItemNode (setName, setID, count) {
     count = count || 0;
     var template = $("li.fav_set_menu_item.template").clone();
     template.removeClass("template");
     $(".setname", template).html(setName);
     $(".setid", template).html(setID);
     $(".setid", template).addClass("set_id_" + setID);
     $(".count", template).html(count);
     enableFavMenuItemClick(template);
     return template;
 }
 
    function doLogOut(){
        $.post(
            "/users/json/user/logout/",
            {},
            onLogOutLoaded,
            "json");
    }
    
    function onLogOutLoaded(data){
        if (data.status == "ok"){
            showLoginInfo(false);
            // removes items from fav set menus
            $("#user-favs-thumbs li").remove();
            showPanel("account");
        }
    }
 
 
 
 
 function showLoginInfo(loggedIn, userName, extraData){
     if(loggedIn){
         $("span.highlight", "#user-is-logged-in").html(userName);
         $("#user-is-logged-in").removeClass("invisible");
         $("#user-is-not-logged-in").addClass("invisible");
         $("#panel-account-view-button").hide();
         // auto - update quick order painel:
         $("#id_full_name", $("#favs-quick-order")).val(extraData["full_name"]);
         $("#id_phone_number", "#favs-quick-order").val(extraData["phone"]);
         $("#id_company", "#favs-quick-order").val(extraData["company"]);
     }else{
         $("#user-is-logged-in").addClass("invisible");
         $("#user-is-not-logged-in").removeClass("invisible");
         $("#panel-account-view-button").show();
         getFavMenuItems().remove();
         $(".favset-title", "#fav-set-text").html(""); 
         var theForm = ("#favs-quick-order");
         // auto - update quick order painel:
            $("#id_full_name",    "#favs-quick-order").val("")
         $("#id_phone_number", "#favs-quick-order").val("")
         $("#id_company", "#favs-quick-order").val("")
         
     }
 }
 // Pass recovery form validation and ajax handling
    $("#pass-recover-form").validate({
     rules: {
         "pass_recovery_form-email": {
             required: true,
             email: true
         }
     },
     messages: {
         "email": "Please enter a valid email address"
     },
     "submitHandler": function(theForm){
         $(".submit", $("#pass-recover-form")).attr("disabled", true);
         sendPassRecovery(theForm);
         return false;
     }
 });
 
 function sendPassRecovery(theForm){
     $.post(
         $(theForm).attr("action"),
         {
             "email": $(theForm.email).val()
         },
         onPassRecoveryResponse,
         "json"
     )
 }
 
 function onPassRecoveryResponse(data){
     $(".submit", $("#pass-recover-form")).attr("disabled", false);
     if(data.status=="error"){
         $("#pass-recover-form").validate().showErrors(normalizeErrors(data.errors));
         
     }else{
         $("#pass-recover-form").validate().showErrors({"email":"Your password has been email to you."});
     }
 }
   
     // Create user form validation and ajax handling
     
    $("#register-form").validate({
     "rules": {
         "email": {
             required: true,
             email: true
         },
         "phone_number":{
             required: true,
             minlength:7,
             maxlength:14
         },
         "name":{
             required: true,
             minlength:3
         },
         "password1":{
             required: true,
             minlength:3
         },
         "password2":{
             required: true,
             minlength:3,
             equalTo:"#id_password1"
         },
         "company":{
             required: true,
             minlength:3
         }
     },
     "messages": {
         "email": "Please enter a valid email address",
         "name": "Plese enter your name",
         "phone_number": "Please enter your phone number, between 7 and 14 characters",
         "password1":{
             "minlength":"Password is required and should be at least 3 characters."
             
         },           
         "password2": {
             "minlength":"Password is required and should be at least 3 characters.",   
             "equalTo": "Both passwords should match"
         },
         "company":{
             "minlength":"Company name should be at least 3 characters.",
             "required": "Company name is required."
         }
     },
     "submitHandler": function(theForm){
         $(".submit", $("#register-form")).attr("disabled", true);
         sendRegisterForm(theForm);
         return false;
     }
 });
 function sendRegisterForm(theForm){
     $.post(
         $(theForm).attr("action"),
         {
             "email": $(theForm.email).val(),
             "name": $(theForm.name).val(),
             "password1": $(theForm.password1).val(),
             "password2": $(theForm.password2).val(),
             "phone_number": $(theForm.phone_number).val(),
             "company": $(theForm.company).val()
         },
         onRegisterResponse,
         "json"
     );
 }
 
 function onRegisterResponse(data){
       if(data.status=="error"){
           var normalized = normalizeErrors(data.errors);
           $("#register-form").validate().showErrors(normalized);
           $(".submit", $("#register-form")).attr("disabled", false);
       }else{ 
           showLoginInfo(true, data.full_name, data);
           showPanel("favorites");
           var newNode = createFavSetMenuItemNode(data.set_name, data.set_id, 0);
         $("#create-user-favorites").after(newNode);
         markFavSetMenuItem(data.set_id, true);
       }
 } 
 
 function hideBlockingMessage(){
     $("#user-message").fadeOut(500, function(){
         $("#user-message-text").html("");
            $("a","#user-message").html("");
     });

 }
 function addBlockingMessage(msgText, buttonText, nextFunc, nextFuncParams){
     $("#user-message-text").html(msgText);
     $("a","#user-message").html(buttonText);
     $("#user-message").show(500, function(){
         $("a","#user-message").click(function(){
             if (!nextFunc){
                 hideBlockingMessage();
             }else{
                  nextFunc.apply(this,nextFuncParams);
             }            
            });
     });

 }
 
 function hideUserManagment(){
     $("#favorites").hide(300);
 }
 
 
 // ==========
 // = PANELS =
 // ==========
 var openSection = null;
 var userFavoritesData = null;
 var userFavoritesSets = [];
 var selectedSetId = -1;
 var panelShown = "";
 
 
 function loadFavSets(){
     if(!isLoggedIn()){
         return;
     }
     $.get("/users/json/product-set/", {}, onFavSetsLoaded, "json");
 }
 
 function getFavMenuItems(){
     return $(".fav_set_menu_item").not("#create-user-favorites").not(".template");
 }
 
 function onFavSetsLoaded (data) {
    var success = (data.status == "ok");
    if (success){
        getFavMenuItems().remove();
        
		opt = "";
        $.each(data.product_sets, function(i, setData){
            // creates set menus:
            var newNode = createFavSetMenuItemNode (  setData.name, setData.id, setData.items.length) ;
            $("#create-user-favorites").after(newNode);
            // for the firt set, we need to load and 
            // create fav node, update the set menu
            if (i == 0){
                setData.status = "ok";
                onUserFavoritesItemsLoaded(setData);
                markFavSetMenuItem(setData.id, true);
            };
            // newNode.hide();
            enableFavMenuItemClick(newNode);
			
			// the best way i found to populate dropboxes without using jquery plugins
			opt += "<option value='"+setData.id+"'>"+setData.name+"</option>";
        });
		
		// append items to dropboxes (quick-order and share)
		$(".share-change-fav-set").html(opt);
		$(".quick-change-fav-set").html(opt);
		
		if(addToFavSetAfterLogin!=null){
			addToFavorites(addToFavSetAfterLogin);
			addToFavSetAfterLogin = null;
		}
		
	   showPanel("favorites");
    }else{
        
    }
 }
 
 function loadUserFavoritesItems(setID, panel){
     //if (setID == selectedSetId)return;
     if(!setID){
         alert("loadUserFavoritesItems with bad setID");
         return;
     }
	 $.get(
		 "/users/json/product-set/" + setID + "/?panel="+panel,
		 {},
		 onUserFavoritesItemsLoaded,
		 "json"
		 );
 }
 
 function onUserFavoritesItemsLoaded(data){
    if(data.status == "ok"){
        var items = data.items;
           var nodes = createFavoriteNodesFromData(items);
           $("#thumbnail-panel").children().remove();
           $.each(nodes,function(i,node){
               node.appendTo("#thumbnail-panel");
           })
		   if(data.go_to_panel == 'order'){
			   markFavSetMenuItem(parseInt(data.id),true,true);
			   addNodesToPreviewPanel($(".order-group"));
		   }else if(data.go_to_panel == 'share'){
			   markFavSetMenuItem(parseInt(data.id),true,true);
			   addNodesToPreviewPanel($(".share-group"));
		   }else{
			   markFavSetMenuItem(parseInt(data.id),true);
		       movePanel(true, $("#favorites-con"));
		   }
    }else{
        
    }
 }

     
 function createFavoriteNodesFromData(items){
     var nodes = [];
     var theNode;
     for(var i = 0; i < items.length; i++){        
         theNode = createFavoriteNodeFromData(items[i]) 
         nodes.push(theNode);
     }
     return nodes;
 }
 
 function createFavoriteNodeFromData(data){
     var node = $("#fav-item-thumb-template").clone();
     node.attr("id", "fav-id-"+data.id);
     $(".fav-obj", node).attr("href", data.url);
        $("img.fav-thumbnail", node).attr("src", data.thumb);
        $("a.fav_delete", node).attr("href", "/users/json/favorites/" + data.id + "/delete/");
        $("div.fav-id-data", node).html(data.id);
        $("div.product-id-data", node).html(data.product_id);
        $("div.fav_name_div", node).html(data.name);
        //$("img", node).hover(function(){
        //    $(this).addClass("favs-thumbnail-rollover");
        //},  function() {
        //    $(this).removeClass("favs-thumbnail-rollover");
        //});
        node.removeClass("invisible");
        $("a.fav_delete", node).click(function(){
              doDeleteItem(data.id);
              return false;
        });
        return node;
 }
 
 function markFavSetMenuItem(itemID, isOn, doNotShowPanel){
     
     if (isOn){
         selectedSetId = parseInt(itemID);
         if (isNaN(selectedSetId)){
                //alert("something is fishy " + selectedSetId +  itemID)
                return;
         }
         var setName = getSetName(selectedSetId);
         var countParent = $(".set_id_" + itemID).parent();
         var setCount =  $(".count", countParent);
         var numInSet = $(".thumbnail-con", "#thumbnail-panel").length;
         setCount.html(numInSet);
         $(".favset-title", "#fav-set-text").html(setName + "("  + setCount.html() + ")");
         $(".current-favset").html(setName);
            if (!doNotShowPanel) showPanel("favorites");
            $(".selected-set-info").html(setName + ":" + itemID);
            $(".delete_me", "#fav_set_menu").remove();
     }
 }


    function getSetName(setID) {
        var baseNode = $(".set_id_" + setID).parent().clone();
        $("div",baseNode).remove()
        return $.trim(baseNode.html());
    };

    var favSharForm = $("#favs-share-form");
    favSharForm.validate({
     "rules": {
         
         "to_email": {
             "required": true,
             "email": true
         },
         "to_name": {
             "required": true
         }
     },
     "messages": {
         "to_email": "Please enter a valid email address"
     },
     "submitHandler": function(theForm){
            $("#do-share-button", $("#favs-share-form")).attr("disabled", true);
            var url = "/users/json/favorites/" + selectedSetId +  "/share/";
         var data = {
                "to_email": $(theForm.to_email).val(),
                "to_name": $(theForm.to_name).val(),
                "send_pdfs": $(theForm.send_pdfs).val(),
                "send_images": $(theForm.send_images).val()
            };
            $.post( url, data, onSendSharingLoaded, "json");
            return false;
     }
 });
 
 function doSendSharing(theForm){
     var url = "/users/json/favorites/" + selectedSetId +  "/share/";
     var data = {
            "to_email": $(theForm).to_email.val(),
            "send_pdfs": $(theForm).send_pdfs.val(),
            "send_images": $(theForm).send_images.val()
        };
        $.post( url, data, onSendSharingLoaded, "json");
 }
 
 function onSendSharingLoaded(data){
     if (data.status=="ok"){
            $(".share-status-msg").html("The email was sent.") 
     }else{
            //$(".share-status-msg", "#favs-share-form").html(data.errors.join("</br> "));
         $(".share-status-msg", "#favs-share-form").html(data.errors);
     }
     $("#do-share-button", $("#favs-share-form")).attr("disabled", false);
 }
 
 function updateQuickOrderInfo(data){
     $.each(["full_name", "email", "company", "phone"], function(i, fName){
         $("input[@name=" + fName + "]", $("#favs-quick-order")).val(data? data[fName] : "");
     });   
 }
 
 $("#favs-quick-order").validate({
        "rules": {
                   "full_name": {
                       "required": true,
                       "minlength": 3
                   },
                   "company": {
                       "required": true,
                       "minlength": 3
                   },
                   "phone": {
                       "required": true,
                       "minlength": 7
                   },
                   "email": {
                       "required": true,
                       "email": true
                   },
                   "time_frame": {
                       "required": true
                   },
                   "quantity": {
                       "required": true
                   },
                   "fabric": {
                       "required": true
                   },
                   "message": {
                       "required": true,
                       "minlength": 3
                   }
               },
               "messages": {
                   "full_name": {
                       'required': "Please provide a full name",
                      "minlength": "A name must be at least 3 characters long"
                   },
                   "company": {
                       "required": "Please provide a company",
                       "minlength": "Company name must be at least 3 characters long."
                   },
                   "phone": {
                       "required": "Please provide your telephone number.",
                       "minlength": "Phone number must be at least 7 characters long"
                   },
                   "email": "Please enter a valid email address.",
                   "time_frame": {
                       "required": "Please select a time frame"
                   },
                   "fabric": {
                       "required": "Please select a fabric"
                   },
                   "quantity": {
                       "required": "Please select a quantity."
                   },
                   "message": {
                       "required": "Please enter your message",
                       "minlength":  " A message must have a few words on it to mean somehting!"
                   }
               },
     "submitHandler": function(theForm){
         $(".submit", $(theForm)).attr("disabled", true);
         doSendQuickOrder(theForm);
         return false;
     }
 });
 
 function doSendQuickOrder(theForm){
     var url = "/users/json/favorites/" + selectedSetId + "/quick-order/";
     var data = {};
     $(":input", $("#favs-quick-order")).each(function(){
            data[$(this).attr("name")] = $(this).val();
        });
        $.post(url, data, onQuickOrderLoaded, "json")
 }
 
 function onQuickOrderLoaded(data){
        $(".submit", $("#favs-quick-order")).attr("disabled", false);
        var success = (data.status == "ok");
     if(success){
            $(".quick-order-status-msg").html("Your order was sent. We will get in touch briefly.")
            $(":input", $("#favs-quick-order")).each(function(){
                $(this).val("");
            });
     }else{
            $(".quick-order-status-msg").html("An error has ocurred. Please try again later or send us an email.")
     }
 }
 
 /** We are using the same preview panel for order and share, both
 *   are set up here
    */
 function addNodesToPreviewPanel (ulNode) {

     ulNode.children().remove();     
     
        $(".thumbnail-con").not("#fav-item-thumb-template").each(function(){
                 
            var node = $("#preview-thumb-template").clone();
            $("img", node).attr("src" , $("img", this).attr("src"));
            var deleteNode = $("#fav-item-thumb-template").clone();
            var id = $(".fav-id-data", this).html();
            var removeNodeURL = "/users/json/favorites/" + id + "/delete/";

             var deleteLink = $(".fav_delete", node);
             deleteLink.attr("href", removeNodeURL);
             deleteLink.click(function(){
                 // check if we can really remove the node (if only one item in fav set, then don't do it)
                    if (doDeleteItem(id)){
                        node.remove();
                    }
                    
                    return false;
                });
            node.removeClass("invisible");
            $(ulNode).append(node);
        });

 }
 
 function getItemId(node){
     return $("div.fav-id-data", node).html()
 }
 
 function movePanel(isUp, toNode, forceNow){		  
              var node = $("#favpanel");
              var id = toNode ? toNode.attr("id") : "hide";
			  
			  fav_height = 300;
			  num_thumbs = $('.thumbnail-con').size()-1;
			  if(num_thumbs>1){
				fav_height += (Math.floor((num_thumbs-1)/5))*138;				
			  }
			 
			  
              var heights = {
                  "favorites-con":[fav_height, 0],
                  "account-con":[780, -200 ],
                  "order-con": [550, 0],
                  "share-con": [550, 0],
                  "delete-con":[280, 0],
                  "rename-con":[280, 0],
                  "hide":[30, 80]
              }
              var h = heights[id][0];
              var b = heights[id][1];
              if (forceNow){
                  node.css({height: h, bottom: b});
              }else{
                  node.animate({height: h, bottom: b}, "fast");
              }      
     }
     
 showPanel = function (panelName){      
     stackTrace(showPanel);
     //log('panelName: ' + panelName);
     
     $("#favpanel").removeClass("invisible");
     var panelSelector = "#" + panelName + "-con";
     $("#fav_set_menu").addClass("invisible");
     $("#favpanel-content").show();
     if(panelName==panelShown) return;
     $(".panelset").not(panelSelector).each(function(){
         $(this).hide();//addClass("invisible");
         
     });
     panelShown = panelName;
     if(!isLoggedIn()){
         $("#account-con").show();
            $("#favorites-con").hide();
         movePanel(true, $("#account-con"));
         return;
     }
     $(panelSelector).show();
     movePanel(true, $(panelSelector));
     
     if(panelName == "order"){
         addNodesToPreviewPanel($(".order-group"))
     }else if (panelName == "share"){
         addNodesToPreviewPanel($(".share-group"));
     }else if (panelName == "favorites"){
         
     }
     if (panelName == "order"){
         // update select box:
         var setChangeSelect = $(".quick-change-fav-set").change(function(){
             var newSetID = $(".quick-change-fav-set option:selected").attr("value");
			 $(".share-change-fav-set").val(newSetID);
             
             if (newSetID.length != -1 ){
                 loadUserFavoritesItems(newSetID, "order");
             }
         })
         
         // getFavMenuItems().each(function(){
         //     
         // })
         
     }
     if (panelName == "share"){
         // update select box:
         var setChangeSelect = $(".share-change-fav-set").change(function(){
             var newSetID = $(".share-change-fav-set option:selected").attr("value");
             $(".quick-change-fav-set").val(newSetID);
             if (newSetID.length != -1 ){
                 loadUserFavoritesItems(newSetID, "share");
             }
         })
         
         // getFavMenuItems().each(function(){
         //     
         // })
         
     }
     hideFavSetMenu()
	 

 }

 function doDeleteItem(itemID){
     // if we only have one item in set, return false:
     
     $.post("/users/json/favorites/" + itemID + "/delete/",
     {},onItemDeleted, "json");
     return $(".thumbnail-con").not("#fav-item-thumb-template").length > 1;
 }
 
 function getItemNode(itemID){
     var theItem = null;
        $(".thumbnail-con ").children().each(function(){ 
         id = "#fav-id-"+itemID;
         if ( $("#fav-id-data ", $(this)).html() == itemID){
             theItem =  $(this);
             return false;
         }
     });
     return theItem;
 }

 function onItemDeleted(data){
     if (data.status=="ok"){
         var node = $("#fav-id-"+data.removed);
         
         node.hide(2000, function(){
             $(this).remove();
			 movePanel(true, $("#favorites-con"));
         });
         var num = data.set_count;
            var countParent = $(".set_id_" + data.set_id).parent();
         var setCount =  $(".count", countParent);
         setCount.html(num.toString());
            markFavSetMenuItem(selectedSetId,true);
     }else if(data.status=="error"){
         alert(data.error);
     }
 }
 
 function isLoggedIn(){  
     return $("#user-is-not-logged-in").hasClass("invisible");
 }
 

 var addToFavSetAfterLogin = null; // when non-logged-in users try to add  an item to fav set the product id is stored here
 function dealWithAddToFavorites(){
     // do we need to intercept the button's click?
     var hasAddButton = $(".add-fav-button").length >0 ;
     if (hasAddButton){
         $(".add-fav-button").click(function(){
			 var loc = window.location.href;
			 
			 var splited = loc.substring(0, loc.lastIndexOf("/") + 1).split("/");
			 var id = splited[splited.length -2];
             if (isLoggedIn()){
                 addToFavorites(id);
                 showPanel("favorites");
                 
             }else{
				 addToFavSetAfterLogin = id;
                 showPanel("favorites");
             }
         })
     }
     
 }
 
 function dealWithQuickOrder(){
     var hasButton = $(".quickorder-fav-button").length >0 ;
     if (hasButton){
         $(".quickorder-fav-button").click(function(){
             if (isLoggedIn()){
                 var splited = window.location.href.split("/");
                 var id = splited[splited.length -2];
                 addToFavorites( id, "order");
             }else{
                 show("account");
             }
         })
     }
 }
 
 function getSelectedSetID(){
     return selectedSetId;
 }
 
 var showPanelAfterFavLoad = null;
 function addToFavorites( productId, directTo){
     showPanelAfterFavLoad = directTo;
     var setID = getSelectedSetID();
     $.post(
         "/users/json/favorites/" + setID + "/" + productId +"/add/",
         {},
         onItemAdded,
         "json"
     );
 }
 
 function changeItemID(href, newID){
     var splited = href.split("/");
     var id = splited[splited.length -2];
     return id;
 }
 
 
 function onItemAdded(data){

     if (data.status=="ok"){
         var node= createFavoriteNodeFromData(data.added);
            if($(".thumbnail-con").children().length>0) {
                // is this product there?
                if ($("img[src=" + data.added.thumb + "]", ".thumbnail-con").length == 0){
                    //$(".thumbnail-con").after(node);
                 node.appendTo("#thumbnail-panel");
                }
                
            }else{
                node.appendTo("#thumbnail-panel");
            }   
            var num = data.set_count;
            var countParent = $(".set_id_" + data.set_id).parent();
          $(".selected-set-info").html(data.set_name +":" + data.set_id);
         //# $(".favset-title", "#fav-set-text").html(data.set_name + "("  + data.set_count + ")");
            markFavSetMenuItem(selectedSetId,true);
            if (showPanelAfterFavLoad){
                showPanel(showPanelAfterFavLoad);
                showPanelAfterFavLoad = null;
            }else{
				movePanel(true, $("#favorites-con"));
			}
     }else{
         alert(data.error);
     }
     
 }
 
$(".product-sm-text").css("position", "relative"); 
$(".product-sm-text").css("bottom", -30);
$(".product-thumb-con").each(function(){
    $(this).parent().mouseover(function(){
		$(".product-sm-text", this).css({"bottom": 0}, "fast");
    });
    $(this).parent().mouseout(function(){
		$(".product-sm-text", this).css({"bottom": -30}, "fast");
    });
})
 // =====================================================
 // = Init stuff, start display conditions and handlers =
 // =====================================================

 $("#create-user-favorites").click(function(){
     if (isLoggedIn()){
         createNewFavSet();
     }
 });
 

 
 function enableFavMenuItemClick(theNode){
        
     $(theNode).click(function(){
        var id = $("div", this).html();
        loadUserFavoritesItems(id, "favorites");
         $("ul", $("#fav-set-text")).toggleClass("invisible");
     });
 }
 getFavMenuItems().each(function(i){
     enableFavMenuItemClick(this)
 });

 $.each(["delete","rename", "share", "order", "account"], function(i,panelName){
     var panelSelector = "#panel-" + panelName + "-view-button";
     $(panelSelector).each(function(){
         $(this).click(function(){
             showPanel(panelName);
         });
     });
 })
 
 $("#yes", "#delete-favset").click(function(){
     doDeleteFavoriteSet();
 });
 
 $("#cancel", "#delete-favset").click(function(){
     showPanel("favorites");
 });
 
 $("#save", "#rename-favset").click(function(){
     doRenameFavoriteSet(selectedSetId);
 });
 
 $("#cancel", "#rename-favset").click(function(){
     showPanel("favorites");
 });
 
 $("#panel-hide-button").click(function(){
     movePanel(false);
 });
 
 $("#panel-show-button").click(function(){
     if(panelShown==""){
         showPanel("favorites");
     }else{
         movePanel(true, $("#favorites-con"));
     }
 });
 
 $("#logout_button").click(function(){
     doLogOut();
 });
 
 $("#keyword").click(function(){
     if($("#keyword").val()=='Search'){
		$("#keyword").val('');
	 }
 });
 // addinitial values to quck form selects:
 // $("[@name=fabric]", "#favs-quick-order");
    $("#favpanel-content").hide();
    
    $("#fav-set-arrow").click(function(){
        if (isLoggedIn()){
            $("ul", $("#fav-set-text")).toggleClass("invisible");
        }else{
            //showPanel("favorites")
        }    
    });
    
    function hideFavSetMenu(){
        $("ul", $("#fav-set-text")).addClass("invisible");
    }
   
    
   // atach delete click to pre loaded favs:
   $(".fav_delete").each(function(i, item){
       
       var href = $(this).attr("href");
       var splited = href.split("/");
       var id = splited[4];    
       $(this).click(function(){
           doDeleteItem(id);
           return false;
       });
    });
    $("#fav-set-img").click(function(){
     if(panelShown==""){
         showPanel("favorites");
     }else{
         movePanel(true, $("#favorites-con"));
     }
    })
    //$(".panelset").hide();
    
   $("#panel-close-button").click(function(){
       $("#favpanel").addClass("invisible");
   })
   
   //movePanel(false, null, true);
   
   // we are only showing the panel if user is logged in or clicks the add to favs
     if (!isLoggedIn()){
     //showPanel("account");
 }else{
     $("#favpanel").removeClass("invisible");
     //$("#panel-account-view-button").hide();
 }
 dealWithAddToFavorites();
 dealWithQuickOrder();
 if (selectedSetId == -1 && isLoggedIn()){
     markFavSetMenuItem( parseInt($("div",$(".fav_set_menu_item")).html()),true, true);
 }
 // =============
 // = debiuggin =
 // =============
 function stackTrace(startingPoint)
    {
     var stackTraceMessage = "Stack trace:\n";
     var nextCaller = startingPoint;
     while(nextCaller)
     {
         stackTraceMessage += getSignature(nextCaller) + "\n";
         nextCaller = nextCaller.caller;
     }
     stackTraceMessage += "\n\n";

     // display message
     log('stackTraceMessage: ' + stackTraceMessage);
     
    }
    function getSignature(theFunction)
    {
     var signature = getFunctionName(theFunction);
     signature += "(";
     for(var x=0; x<theFunction.arguments.length; x++)
     {
         // trim long arguments
         var nextArgument = theFunction.arguments[x];
         if(nextArgument.length > 30)
             nextArgument = nextArgument.substring(0, 30) + "...";

         // apend the next argument to the signature
         signature += "'" + nextArgument + "'"; 

         // comma separator
         if(x < theFunction.arguments.length - 1)
             signature += ", ";
     }
     signature += ")";
     return signature;
    }
    function getFunctionName(theFunction)
    {
     // mozilla makes it easy. I love mozilla.
     if(theFunction.name)
     {
         return theFunction.name;
     }

     // try to parse the function name from the defintion
     var definition = theFunction.toString();
     var name = definition.substring(definition.indexOf('function') + 8,definition.indexOf('('));
     if(name)
         return name;

     // sometimes there won't be a function name 
     // like for dynamic functions
     return "anonymous";
    }
    
    
    $("#login_link").click(function(){
        showPanel("thumbnail")
    });
    $("#fav-set-img").click(function(){
        showPanel("favorites")
    });
    window.showPanel = showPanel;
});