/// <reference path="jQuery.intellisense.js" />
/// <reference name "MicrosoftAjax.js" assembly="System.Web.Extensions" />

(function($) {

	// Debug
	if ( !$.browser.safari && typeof window.console !== 'undefined' && typeof window.console.log === 'function' )
	{	// Use window.console
		$.log = window.console.log;
	}
	else
	{	// Don't use anything
		$.log = function ( ) { };
	}

  $.fn.ajaxPreloader = function(options) {
  
    var options = $.extend({}, $.fn.ajaxPreloader.defaults, options);
  
    ajaxPreloader = function(preloader, options) {
      this.preloader = preloader;
      this.options = options;
      this.init();
    };
    
    ajaxPreloader.prototype = {
    
      init : function() {
        if (this.preloader) {
          $(this.preloader).hide();
        }      
        if (Sys && Sys.WebForms) {
          Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(Function.createDelegate(this, this.show));
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Function.createDelegate(this, this.hide));
        }
        $(this.preloader).ajaxStart(Function.createDelegate(this, this.show));
        $(this.preloader).ajaxStop(Function.createDelegate(this, this.hide));
        $(this.preloader).ajaxError(Function.createDelegate(this, this.hide));
      },
    
      show : function() {
        if (this.preloader) {
          $(this.preloader).show();
          $(this.preloader).removeClass(this.options.inactiveCssClass);
          $(this.preloader).addClass(this.options.activeCssClass);
        }
      },    
      
      hide : function() {
        if (this.preloader) {
          $(this.preloader).hide();
          $(this.preloader).removeClass(this.options.activeCssClass);
          $(this.preloader).addClass(this.options.inactiveCssClass);
        }
      }      
    };
    
    $(this).each(function() {
      new ajaxPreloader(this, options);
    });
	};			
	
	$.fn.ajaxPreloader.defaults = {
    activeCssClass : '',
    inactiveCssClass : ''	
	};

  $.fn.captcha = function(options) {
  
    options = $.extend({}, $.fn.captcha.defaults, options);
  
    captcha = function(image, options) {
      this.image = image;      
      this.imageKey;
      this.options = options;
      this.init();
    };
    
    captcha.prototype = {
      
      init : function() {
        if (this.options.reloadButton) {
          $(this.options.reloadButton).click(Function.createDelegate(this, this.reload));
        }
        this.reload();
      },      
      
      reload : function() {
        this.sendImageRequest();
      },
      
      getImageKey : function() {
        return this.imageKey;
      },
      
	    errorRequestHandler : function(response, result) {
	      $.log('WARN', response.responseText);
	    }, 
	        
      sendImageRequest : function() {
		      params = {request: this.options.generateImageRequest};
	        $.getMSJSON(this.options.serviceUrl, params, 
	                    Function.createDelegate(this, this.imageRequestCallback),
	                    Function.createDelegate(this, this.errorRequestHandler));
      },     
    
      imageRequestCallback : function(data, result) {
        this.imageKey = data;
        if (this.options.keyCodeInput)
        {
          $(this.options.keyCodeInput).val(this.imageKey);
        }
        this.loadImage();
      },
      
      loadImage : function() {
        if (this.image && this.imageKey) {
          this.image.src = String.format(this.options.imageUrlTemplate, this.options.serviceUrl, this.imageKey);
        }
      }
    };
    
    return new captcha($(this).get(0), options);
	};	
		
	$.fn.captcha.defaults = {
    serviceUrl : '',
    generateImageRequest : 'GenerateImage',
    imageUrlTemplate : '{0}?request=GetImage&key={1}',
    keyCodeInput : ''
	};			
	
	
  $.fn.collapsableBlock = function(collapsableArea, controller, controllerText, stateField, options) {
  
    options = $.extend({}, $.fn.collapsableBlock.defaults, options);
    
    $(this).each(function() {
      if (stateField) {
        state = Boolean.parse($(stateField).val());
        if (state) {
          $(collapsableArea, this).show();
          $(this).addClass(options.expandedClass);
          $(controllerText, this).text(options.expandedText);
        }
        else {
          $(collapsableArea, this).hide();
          $(this).removeClass(options.expandedClass);
          $(controllerText, this).text(options.collapsedText);
        }
      }

      $(controller, this).unbind('click').bind('click', {root : this}, function(context) {
        root = context.data.root;
        $($(collapsableArea, root).toggle().parent()).toggleClass(options.expandedClass);
        if (stateField) {
          state = !Boolean.parse($(stateField).val());
          $(stateField).val(state);
          if(state)
          {
            $(controllerText, this).text(options.expandedText);
          }
          else
          {
            $(controllerText, this).text(options.collapsedText);
          }
        }
      });
    });
  };
  
  $.fn.collapsableBlock.defaults = {
    expandedClass : 'expanded',
    expandedText : 'collapse',
    collapsedText : 'expand'
	};
  
  $.fn.mainMenu = function(options) {
  
    options = $.extend({}, $.fn.mainMenu.defaults, options);
  
    mainMenu = function(menuArea, options) {
      this.menuArea = menuArea;
      this.items;
      this.options = options;
      this.init();
    };
    
    mainMenu.prototype = {
      
      init : function() {
        $(this.menuArea).setTemplateURL(this.options.templateUrl, null, {filter_data: false});
        if (typeof Sys != undefined && Sys && Sys.WebForms) {
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Function.createDelegate(this, this.update));
        }        
      },      
      
      update : function() {
        this.sendItemsRequest();
      },
      
	    errorRequestHandler : function(response, result) {
	      $.log('WARN', response.responseText);
	    },
	        
      sendItemsRequest : function() {
		      params = {request: this.options.getItemsRequest};
	        $.getMSJSON(this.options.serviceUrl, params, 
	                    Function.createDelegate(this, this.itemsRequestCallback),
	                    Function.createDelegate(this, this.errorRequestHandler));
      },     
    
      itemsRequestCallback : function(data, result) {
        if (data) {
          this.items = data;
          this.buildMenu();
        }
      },
      
      buildMenu : function() {
        $(this.menuArea).processTemplate(this.items);
      }
    };
    
    $(this).each(function() {
      return new mainMenu(this, options);
    });
	};	
		
	$.fn.mainMenu.defaults = {
    serviceUrl : '',
    templateUrl : '',
    getItemsRequest : 'GetMainMenu'
	};			
	
  $.fn.buyButton = function(productID, variantID, options) {
  
    buyProductButton = function(button, productID, variantID, options) {
      this.button = button;
      this.options = options;
      this.productID = productID;
      this.variantID = variantID;
      this.basketContent = null;
      this.init();
    };
    
    buyProductButton.prototype = {
    
      init : function() {
        $(this.button).click(Function.createDelegate(this, this.buttonClickHandler));
      },
      
      errorRequestHandler : function(response, result) {
	      $.log('WARN', response.responseText);
	    },
      
      buttonClickHandler : function() {
        params = {request: this.options.addProductRequest};
        if (this.productID) {
          params.productID = this.productID;
        }
        if (this.variantID) {
          params.variantID = this.variantID;
        }       
        if (this.options.quantityField) {
          params.quantity = $(this.options.quantityField).val();
        }      
        $.getMSJSON(this.options.serviceUrl, params, 
                    Function.createDelegate(this, this.buyCompleteHandler),
                    Function.createDelegate(this, this.errorRequestHandler));
      },
      
      buyCompleteHandler : function(data, result) {
        if (typeof data != undefined) {
          if (data.IsSuccess) {
            this.updateBuyEnable();
            this.updateBasketView();
            this.showSuccessMessage();
            this.getBasketContent();
          }
          else {
            this.showErrorMessage(data.Message);
          } 
        }          
      },
      
      showErrorMessage : function (message) {
        $('form').messageBox(null, {
          messageType: 'Error', 
          top: 10, 
          left: '900px',
          width: 350, 		      
          autoClose: true,
          title: "You've got some errors.",
          modal : false},
          $.generateList, {list: [message]});
      },
            
      showSuccessMessage : function () {
        this.basketContent = $.create('div', {});
        this.basketContent.setTemplateURL(this.options.basketContentTemplate, null, {filter_data: false});
      },      
      
      getBasketContent : function () {
        params = {request: this.options.getDetailedContentRequest};   
                    
        $.getMSJSON(this.options.serviceUrl, params,
                    Function.createDelegate(this, this.getBasketContentSuccess),
                    Function.createDelegate(this, this.errorRequestHandler));
      },
      
      getBasketContentSuccess : function (data, result) {
        if (typeof data != undefined) {
          this.basketContent.processTemplate(data);
          $.scrollTo(0, 0, {speed:1000, onAfter : Function.createDelegate(this, this.scrollCompletedHandler)});
				}
      },
      
      scrollCompletedHandler : function() {
        $('div.Container').messageBox(null, {
          messageType: 'Basket', 
          contentClassName: 'Product', 
          containerClassName: 'PopUpContainer Basket-Updated', 
          title: 'New product has been added',
          top: 110, 
          left: '625px', 
          width: 350, 
          autoClose: true, 
          modal : false, 
          showArrow : true}, 
          this.basketContent);
			},
      
      updateBuyEnable : function() {
        if (this.options.buyEnable) {
          params = {request: this.options.buyEnableRequest};
          if (this.productID) {
            params.productID = this.productID;
          }
          if (this.variantID) {
            params.variantID = this.variantID;
          }
          
          $.getMSJSON(this.options.serviceUrl, params, 
            Function.createDelegate(this, this.updateBuyEnableHandler), 
            Function.createDelegate(this, this.errorRequestHandler));
        }
      },
      
      updateBuyEnableHandler : function(data, result) {
        if (typeof data != undefined) {
          if (this.options.buyEnable && data === false) {
            $(this.options.buyEnable).remove();
          }
        }      
      },
      
      updateBasketView : function() {
        if (this.options.basketView || this.options.basketViewTemplate) {
          basketView = $(this.options.basketView);
          basketView.setTemplateURL(this.options.basketViewTemplate, null, {filter_data: false});
          params = {request: this.options.getContentRequest};   
          
          $.getMSJSON(this.options.serviceUrl, params, function(data, result) {
            if (typeof data != undefined) {
                basketView.processTemplate(data);
            }
          }, Function.createDelegate(this, this.errorRequestHandler));
        }
      }
    };
    
    $(this).each(function() {
      new buyProductButton(this, productID, variantID, $.extend({}, $.fn.buyButton.defaults, options));
    });    
  };
    	
	$.fn.buyButton.defaults = {
    serviceUrl : '',
    getStartedUrl : '',
    quantityField : null,
    getContentRequest : 'GetContent',
    getDetailedContentRequest : 'GetDetailedContent',
    buyEnableRequest : 'BuyEnable',
    addProductRequest : 'AddProduct',
    basketView : '#basketViewArea',
    basketViewTemplate : '',
    basketContentTemplate : '',
    buyEnable : null
	};	
	  
  $.fn.basketView = function(settings) {
  
    basketView = function(basketArea, settings) {
      this.basketArea = basketArea;
      this.settings = settings;
      this.init();
    };
    
    basketView.prototype = {
    
      init : function() {
        $(this.basketArea).setTemplateURL(this.settings.templateUrl, null, {filter_data: false});
        if (typeof Sys != undefined && Sys && Sys.WebForms) {
          Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Function.createDelegate(this, this.update));
        }
        this.initializeGetStartedMessage();         
      },
      
      update : function() {
        params = {request: this.settings.getContentRequest};   

        $.getMSJSON(this.settings.serviceUrl, params, 
                      Function.createDelegate(this, this.updateComplete),
                      Function.createDelegate(this, this.errorRequestHandler));
      },
      
      updateComplete : function(data, result) {  
        if (typeof data != undefined) {
            $(this.basketArea).processTemplate(data);
        }
        this.initializeGetStartedMessage();        
      },
      
      initializeGetStartedMessage : function(){
        $(".basketGetStarted", this.basketArea).bind('click', Function.createDelegate(this, this.getGetStartedMessage));
      },
      
      getGetStartedMessage : function(){
        var content = $.create('div', {});
        content.setTemplateURL(this.settings.getStartedUrl, null, {filter_data: false});
        content.processTemplate();
        $('form').messageBox(null, {
              messageType: 'Notification', 
              top: 10, 
              width: 350,
              autoClose: false,
              title: "How do I get started?",
              modal : false}, 
              content);        
      },
            
      errorRequestHandler : function(response, result) {
	      $.log('WARN', response.responseText);
	    }            
    };
    
    $(this).each(function() {
      new basketView(this, $.extend({}, $.fn.basketView.defaults, settings));
    });
	};			
	
	$.fn.basketView.defaults = {
    serviceUrl : '',
    templateUrl: '',
    getContentRequest : 'GetContent'
	};	
	
})(jQuery);

reviewEditor = function(listing, options) {
  this.reviewID = null;
  this.listing = listing;
  this.options = $.extend({}, reviewEditor.defaults, options);
  this.popup = null;
  this.captcha = null;
  this.content = null;
  this.init();
};
    
reviewEditor.prototype = {

  init : function() {
    options = this.options;
    editor = this;
    listing = this.listing;
    $(String.format('a[rel^={0}]', options.editUrlPrefix), $(this.listing.placeHolder)).each(function() {
      reviewID = this.rel.match(options.editUrlPattern);
      if (reviewID && reviewID.length > 0) {
        reviewID = reviewID[1];
      }
      else {
        reviewID = null;
      }
      $(this).bind('click', {reviewID : reviewID}, function(e) {
        editor.showPopup(e.data.reviewID);
      });
    });
    $(String.format('a[rel^={0}]', options.deleteUrlPrefix), $(this.listing.placeHolder)).each(function() {
      reviewID = this.rel.match(options.deleteUrlPattern);
      if (reviewID && reviewID.length > 0) {
        reviewID = reviewID[1];
      }
      $(this).click(function() {
        if (confirm('Are you sure want to delete your review?')) {
          listing.deleteItem(reviewID);
        }
      });
    });
    if (this.options.addLink) {      
      $(this.options.addLink).unbind('click').click(function() {
        editor.showPopup();
      });      
    }  
  },
      
  errorRequestHandler : function(response, result) {
    $.log('WARN', response.responseText);
  },     

  loadData : function() {
    if (this.reviewID) {
      params = {request: this.options.getByIdRequest, id: this.reviewID};
    }
    else {
      params = {request: this.options.newRequest};
    }
    $.getMSJSON(this.options.serviceUrl, params, 
                Function.createDelegate(this, this.loadDataHandler),
                Function.createDelegate(this, this.errorRequestHandler));
  },

  loadDataHandler : function(data, result) {
    this.content.processTemplate(data);
    this.popup = this.createPopup();

    this.initRatingField();
    this.initCaptcha();
    
    $('#saveReview', this.content).click(Function.createDelegate(this, this.saveData));
    $('#cancelReview', this.content).click(Function.createDelegate(this, this.hidePopup));      
  },
  
  initRatingField : function() {
    $('#ratingField', this.content).numeric();
    $('#ratingField', this.content).upDownField({
      upButton: '#ratingUp', 
      downButton: '#ratingDown'}, {
      minValue: 1,
      maxValue: 5,
      defaultValue : 5
    });      
  },
  
  initCaptcha : function() {
    this.captcha = $('#reviewCaptcha', this.content).captcha({
      serviceUrl: this.options.captchaServiceUrl, 
      reloadButton: $('#reloadCaptcha', this.content)
    });
  },
  
  createPopup : function() {
    if (this.reviewID) {
      title = 'EDIT REVIEW';
    }
    else {
      title = 'ADD REVIEW';
    }      
    return $('form').messageBox(null, {
                    messageType: '',
                    contentClassName: '',
                    title: title,
                    width: 400, 
                    top: 200, 
                    modal: true, 
                    autoClose: false, 
                    innerRound: 0}, this.content);
  },
  
  showPopup : function(reviewID) {
    this.reviewID = reviewID;
    this.content = $.create('div', {});
    this.content.setTemplateURL(this.options.templateUrl, null, {filter_data: false});
    this.loadData();
  },
  
  hidePopup : function() {
    if (this.popup) {
      this.popup.hide();
    }
  },

  saveData : function() {
    params = {
      request : this.options.saveRequest,
      productID : this.options.productId,
      content : Url.encode($('#contentField', this.content).val()),
      rating : $('#ratingField', this.content).val(),
      captchaKey : this.captcha.getImageKey(),
      captchaCode : $('#captchaCode', this.content).val()
    };
    if (this.reviewID) {
      params.id = this.reviewID;
    }
    $.getMSJSON(this.options.serviceUrl, params, 
                Function.createDelegate(this, this.saveDataHandler),
                Function.createDelegate(this, this.errorRequestHandler));  
  },

  saveDataHandler : function(data, result) {
    if (data) {
      if (data.IsValid) {
        this.hidePopup();
        this.listing.retrieveData();
        $('form').messageBox(null, {
          messageType: 'Notification', 
          title: 'Success',
          width: 350, 
          top: 10, 
          modal: false, 
          autoClose: true}, 
          '<div class="SysInfo"><p>Your review has been saved successfully.</p></div>');
      }
      else {
		    $('form').messageBox(null, {
		      messageType: 'Error', 
		      top: 10, 
		      title: "You've got some errors.",
		      width: 350, 		      
		      autoClose: true,
		      modal : false}, 
          $.generateList, {list: data.ErrorMessages});
        this.captcha.reload();
      }
    }
  }      
};

reviewEditor.defaults = {
  productId : null,
  serviceUrl : '',
  templateUrl : '',
  editUrlPattern : /edit_review_(\d+)/,
  editUrlPrefix : 'edit_review_',
  deleteUrlPattern : /delete_review_(\d+)/,
  deleteUrlPrefix : 'delete_review_',  
  captchaServiceUrl : '',
  getByIdRequest : 'GetById',
  newRequest : 'New',
  saveRequest : 'Save'
};

addReviewControl = function(addReviewArea, alternativeArea, options) {
  this.addReviewArea = addReviewArea;
  this.alternativeArea = alternativeArea;
  this.options = $.extend({}, addReviewControl.defaults, options);
  this.init();
};

addReviewControl.prototype = {
  
  init : function() {
    this.switchAreas();
    if (Sys && Sys.WebForms) {
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Function.createDelegate(this, this.switchAreas));
    }  
  },

  switchAreas : function() {
    params = {request: this.options.availabilityRequest};
    $.getMSJSON(this.options.serviceUrl, params, 
                Function.createDelegate(this, this.availabilityRequestHandler),
                Function.createDelegate(this, this.errorRequestHandler));        
  },  
      
  errorRequestHandler : function(response, result) {
    $.log('WARN', response.responseText);
  },

  availabilityRequestHandler : function(response, result) {
    if (response && response === true) {
      $(this.addReviewArea).show();
      $(this.alternativeArea).hide();
    }
    else {
      $(this.addReviewArea).hide();
      $(this.alternativeArea).show();    
    }
  }
};

addReviewControl.defaults = {
  serviceUrl : '',
  availabilityRequest : 'IsReviewAvailable'
};

buyProduct = function(productID, variantID, options) {
  this.options = $.extend({}, buyProduct.defaults, options);
  this.productID = productID;
  this.variantID = variantID;
  this.basketContent = null;
  this.buy();
};
    
buyProduct.prototype = {
  
  errorRequestHandler : function(response, result) {
    $.log('WARN', response.responseText);
  },
  
  buy : function() {
    params = {request: this.options.addProductRequest, quantity: this.options.quantity};
    if (this.productID) {
      params.productID = this.productID;
    }
    if (this.variantID) {
      params.variantID = this.variantID;
    }       

    $.getMSJSON(this.options.serviceUrl, params, 
                Function.createDelegate(this, this.buyCompleteHandler),
                Function.createDelegate(this, this.errorRequestHandler));
  },
  
  buyCompleteHandler : function(data, result) {
    if (typeof data != undefined) {
      if (data.IsSuccess) {
        this.updateBuyEnable();
        this.updateBasketView();
        this.showSuccessMessage();
        this.getBasketContent();
      }
      else {
        this.showErrorMessage(data.Message);
      } 
    }          
  },
  
  showErrorMessage : function (message) {
    $('form').messageBox(null, {
      messageType: 'Error', 
      top: 10,
      title: "You've got some errors.",
      left: '900px',
      width: 350, 		      
      autoClose: true,
      modal : false}, 
      $.generateList, {list: [message]});
  },
        
  showSuccessMessage : function () {
    this.basketContent = $.create('div', {});
    this.basketContent.setTemplateURL(this.options.basketContentTemplate, null, {filter_data: false});
  },      
  
  getBasketContent : function () {
    params = {request: this.options.getDetailedContentRequest};   
                
    $.getMSJSON(this.options.serviceUrl, params,
                Function.createDelegate(this, this.getBasketContentSuccess),
                Function.createDelegate(this, this.errorRequestHandler));
  },
  
  getBasketContentSuccess : function (data, result) {
    if (typeof data != undefined) {
      this.basketContent.processTemplate(data);
      $.scrollTo(0, 0, {speed:1000, onAfter : Function.createDelegate(this, this.scrollCompletedHandler)});
		}
  },
      
  scrollCompletedHandler : function() {
    $('div.Container').messageBox(null, {
      messageType: 'Basket', 
      contentClassName: 'Product', 
      containerClassName: 'PopUpContainer Basket-Updated', 
      title: 'New product has been added',
      top: 110, 
      left: '625px', 
      width: 350, 
      autoClose: true, 
      modal : false, 
      showArrow : true}, 
      this.basketContent);
	},
  
  updateBuyEnable : function() {
    if (this.options.buyEnable) {
      selectorToUpdate = this.options.buyEnable;
      params = {request: this.options.buyEnableRequest};
      if (this.productID) {
        params.productID = this.productID;
      }
      if (this.variantID) {
        params.variantID = this.variantID;
      }
      
      $.getMSJSON(this.options.serviceUrl, params, function(data, result) {  
        if (typeof data != undefined && data === false) {
          $(selectorToUpdate).each(function() {
            $(this).remove();
          });
        }
      }, Function.createDelegate(this, this.errorRequestHandler));
    }
  },
  
  updateBasketView : function() {
    if (this.options.basketView || this.options.basketViewTemplate) {
      basketView = $(this.options.basketView);
      basketView.setTemplateURL(this.options.basketViewTemplate, null, {filter_data: false});
      params = {request: this.options.getContentRequest};   
      
      $.getMSJSON(this.options.serviceUrl, params, function(data, result) {
        if (typeof data != undefined) {
            basketView.processTemplate(data);
        }
      }, Function.createDelegate(this, this.errorRequestHandler));
    }
  }
};
  	
buyProduct.defaults = {
  serviceUrl : '',
  quantity : 1,
  getContentRequest : 'GetContent',
  getDetailedContentRequest : 'GetDetailedContent',
  getOrderItemRequest : 'GetOrderItem',
  buyEnableRequest : 'BuyEnable',
  addProductRequest : 'AddProduct',
  basketView : '#basketViewArea',
  basketViewTemplate : '',
  basketContentTemplate : '',
  buyEnable : null
};

function setFocus(input) {
  $(input).each(function() {
    this.focus();
    this.select();
  });
}

function setStartPage(element, url)
{

  if (document.all)
  {
    element.style.behavior='url(#default#homepage)';
    element.setHomePage(url);

  }
  else
    if(!document.layers)
    {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
      navigator.preference("browser.startup.homepage", url); 
    }
}

function addBookmark()
{
  var url = location.href;
  var title = document.title;

  //Gecko
  if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) 
  {
    window.sidebar.addPanel (title, url, "");
  }
  //IE4+
  else 
  {
    if (typeof window.external == "object") 
    { 
      window.external.AddFavorite(url, title);
    }
    else 
    {
      if (window.opera && document.createElement)
      {
        var a = document.createElement('A');
        if (!a) return false; //IF Opera 6
        a.setAttribute('rel','sidebar');
        a.setAttribute('href',url);
        a.setAttribute('title',title);
        a.click();
      }
      else 
      {
        return false;
      }
    }
  }
  //Opera7+

  return true;
}

function  treeExpand(namingPrefix, id_item)
{    
    var e = document.getElementById(namingPrefix + 'r_' + id_item);
    var state = document.getElementById(namingPrefix + 'node_state_' + id_item);
    var anc = document.getElementById(namingPrefix + 'a_' + id_item);
    if (e != null) {
        if (e.style.display != 'block') {
            e.style.display = 'block';
            if (anc != null) {            
              anc.src = anc.src.replace('plus', 'minus');
            }
            if (state != null) {
              state.value = '1';
            }
        } else {
            e.style.display = 'none';
            if (anc != null) {            
              anc.src = anc.src.replace('minus', 'plus');
            }
            if (state != null) {
              state.value = '0';
            }
        }
    }
}

(function($) {

  forgotPassword = function(button, options) {
    this.button = button;
    this.content = null;
    this.popup = null;
    this.options = $.extend({}, this.defaults, options)
    this.init();
  };
    
  forgotPassword.prototype = {
    init : function() {
      $(this.button).click(Function.createDelegate(this, this.showForgotPasswordPopup));
    },
    
    
    showForgotPasswordPopup : function() {
      if(!this.content)
      {
        this.createContent();
      }
      //for some reason this handler should be added each time we create the popup
      $('#sendLogin', this.content).click(Function.createDelegate(this, this.sendPasswordClickHandler));
      this.popup = this.createForgotPasswordPopup();
      
    },
    
    createForgotPasswordPopup : function() {
      return $('form').messageBox(null, {
                      messageType: '',
                      contentClassName: '',
                      title: 'FORGOT PASSWORD',
                      width: 400, 
                      top: 200, 
                      modal: true, 
                      autoClose: false, 
                      innerRound: 0}, this.content);
    },

    createContent : function() {
      this.content = $.create('div', {});
      this.content.setTemplateURL(this.options.templateUrl, null, {filter_data: false});
      this.content.processTemplate(null);
    },
    
    sendPasswordClickHandler : function() {
      var loginText = $('#login', this.content);
      params = {request: this.options.forgotPasswordRequest, login : loginText.val()};

      $.getMSJSON(this.options.serviceUrl, params, 
                  Function.createDelegate(this, this.requestCompleteHandler),
                  Function.createDelegate(this, this.requestErrorHandler));
    },
    
    requestCompleteHandler : function(data, result) {
      if (typeof data != undefined) {
        if (data.IsSuccess) {
          this.showSuccessMessage();
        }
        else {
          this.showErrorMessage(data.Message);
        }
      }
    },
    
    requestErrorHandler : function(response, result) {
      $.log('WARN', response.responseText);
    },
    
    showErrorMessage : function (message) {
      $('form').messageBox(null, {
        messageType: 'Error', 
        top: 10, 
        width: 350,
        autoClose: true,
        title: "You've got some errors.",
        modal : false}, 
        $.generateList, {list: [message]});
    },
    
    showSuccessMessage : function () {
      $('form').messageBox(null, {
        messageType: 'Notification',
        title: 'Success',
        top: 10,
        width: 350,
        autoClose: true,
        modal : false}, 
        this.options.successHtml);
    },
    
    defaults : {
      serviceUrl : '',
      forgotPasswordRequest : 'ForgotPassword',
      templateUrl : '',
      successHtml : '<div class="SysInfo"><p>Your password has been sent to your email.</p></div>'
    }
  };

  $.fn.forgotPassword = function(options) {
    $(this).each(function() {
      new forgotPassword(this, options);
    });    
  };

})(jQuery);

(function($) {

  sendLinkToFriend = function(button, productID, variantID, options) {
    this.button = button;
    this.content = null;
    this.popup = null;
    this.captcha = null;
    this.productID = productID;
    this.variantID = variantID;
    this.options = $.extend({}, this.defaults, options)
    this.init();
  };
    
  sendLinkToFriend.prototype = {
    init : function() {
      $(this.button).click(Function.createDelegate(this, this.showSendLinkPopup));
    },
    
    
    showSendLinkPopup : function() {
      if(!this.content)
      {
        this.createContent();
      }
      
      //for some reason all handlers should be added each time we create the popup, 
      //and as some handlers are added for the captcha (reload image) (in initCaptcha), it should be initialized again.
      this.initCaptcha();
      $('#sendLink', this.content).click(Function.createDelegate(this, this.sendLinkClickHandler));
      this.popup = this.createSendLinkPopup();
    },
    
    hideSendLinkPopup : function() {
      if (this.popup) {
        this.popup.hide();
      }
    },
    
    createSendLinkPopup : function() {
      return $('form').messageBox(null, {
                      messageType: '',
                      contentClassName: '',
                      title: 'SEND LINK',
                      width: 400, 
                      top: 200, 
                      modal: true, 
                      autoClose: false, 
                      innerRound: 0}, this.content);
    },

    createContent : function() {
      this.content = $.create('div', {});
      this.content.setTemplateURL(this.options.templateUrl, null, {filter_data: false});
      this.content.processTemplate(null);
    },
    
    initCaptcha : function() {
      this.captcha = $('#sendLinkCaptcha', this.content).captcha({
        serviceUrl: this.options.captchaServiceUrl, 
        reloadButton: $('#reloadCaptcha', this.content)
      });
    },
    
    sendLinkClickHandler : function() {
      params = {
        request: this.options.sendLinkRequest,

        captchaCode : $('#captchaCode', this.content).val(),
        captchaKey : this.captcha.getImageKey(),
        friendMail : $('#friendMail', this.content).val(),
        friendName : $('#friendName', this.content).val(),
        userMessage : $('#userMessage', this.content).val(),
        userName : $('#userName', this.content).val(),

        productID : this.productID,
        variantID : this.variantID
      };

      $.getMSJSON(this.options.serviceUrl, params, 
                  Function.createDelegate(this, this.requestCompleteHandler),
                  Function.createDelegate(this, this.requestErrorHandler));
    },
    
    requestCompleteHandler : function(data, result) {
      if (typeof data != undefined) {
        if (data.IsValid) {
          this.showSuccessMessage();
          this.hideSendLinkPopup();
        }
        else {
          this.showErrorMessage(data);
        }
      }
    },
    
    requestErrorHandler : function(response, result) {
      $.log('WARN', response.responseText);
    },
    
    showErrorMessage : function (data) {
    
      this.captcha.reload();
    
      $('form').messageBox(null, {
        messageType: 'Error', 
        top: 10, 
        width: 350,
        autoClose: true,
        title: "You've got some errors.",
        modal : false}, 
        $.generateList, {list: data.ErrorMessages});
    },
    
    showSuccessMessage : function () {
    
      //this.captcha.reload(); instead we hide the initial popup in requestCompleteHandler
    
      $('form').messageBox(null, {
        messageType: 'Success',
        title: 'Success',
        top: 10,
        width: 350,
        autoClose: true,
        modal : false}, 
        this.options.successHtml);
    },
    
    defaults : {
      serviceUrl : '',
      sendLinkRequest : 'sendLink',
      templateUrl : '',
      captchaServiceUrl : '',
      successHtml : '<div class="SysInfo"><p>A message has been sent to your friend\'s email.</p></div>'
    }
  };

  $.fn.sendLinkToFriend = function(productID, variantID, options) {
    $(this).each(function() {
      new sendLinkToFriend(this, productID, variantID, options);
    });    
  };

})(jQuery);