/*
 * File:					browse.js
 * Title:					Browse Class
 * Description:		Contains our core functions of the Browse feature
 * Author:				Dan Bair, Florentine Design (www.florentinedesign.com)
 */


 /*	BROWSE CLASS
--------------------------------------------------------->>
--------------------------------------------------------->>
 */

var Browse = {
  /*
	 * @class params
	 *    ajaxurl :: where we send ajax requests
	 *    waist   :: customer's selected waist size
	 *    length  :: customer's selected length
	 *
	 *
	 *
	 */
	ajaxurl : 'customizer.php',
	waist   : null,
	lwaist  : null,
	length  : null,
	kilt		: null,
	color		: 0,
	beergut : 1,
	in_stock : null,
	iv   : null,
	ap_chk : false,

	/*
	 * init
	 */
  init : function() {
    this.iv = setInterval( function () {
      clearInterval(Browse.iv) ;
      try {
        if ($('waist').value > 0) {
          Browse.waist = $('waist').value ;
          if ((Browse.waist % 2) == 1) Browse.lwaist = Browse.waist ;
        }

      }catch(e){}

      try {
        if ($('length').value > 0) Browse.length = $('length').value ;
      }catch(e){}
      Browse.checkSubmit();
      try {
        _k = Cook.get('kiltChoice') ;
        if (_k) Browse.kilt = _k ;
      }catch(e){}
    }, 2000) ;
  },
	/*
	 * setWaist :: sets the waist locally and checks to see if
	               we need to pop up the waist info
	 */
  setWaist : function(_waist) {
    _waist = (_waist == undefined) ? $('waist').value : _waist ;
    this.waist = _waist ;
    if ((this.waist % 2) == 1) {
      this.lwaist = this.waist ;
    }else{
      this.lwaist = null ;
    }

    if (!Cook.get('hasChosenWaist')) {
      Cook.set({ name : 'hasChosenWaist', value: 'true', date : { days : 365 }}) ;
      this.ajaxRequest('action=getWaistPop1', {}, 'showpopup') ;
    }
    this.checkSubmit();
  },
  viewKilt : function( pid, kcode) {
    this.kilt = kcode ;
    Cook.set({ name : 'kiltChoice', value : this.kilt }) ;
    if (this.waist > 0 && this.length > 0) {
      this.kilt = kcode ;
      this.refreshCustomizerUi() ;
    }else{
      window.location = 'custom_product.php?products_id=' + pid ;
    }


  },

  colorChoice : function (_color) {

    try {
      var _add = this.in_stock[Number(this.color)] > 0 ? 'cavail' : 'cunavail' ;
      Element.removeClassName( 'color_' + this.color , 'csel');
      Element.addClassName( 'color_' + this.color , _add);
    } catch(e){};
    var _remove = this.in_stock[Number(_color)] > 0 ? 'cavail' : 'cunavail' ;
  	Element.removeClassName( 'color_' + _color , _remove);
  	Element.addClassName( 'color_' + _color, 'csel');
    this.color = _color ;
  },
  initInColors : function (_args) {
    this.in_stock = _args ;
  },
  /*
	 * setLength :: sets the length locally and checks to see if
	               we need to pop up the length info
	 */
  setLength : function(_length) {
    _length = (_length == undefined) ? $('length').value : _length ;
    this.length = _length ;
    if (!Cook.get('hasChosenLength')) {
      Cook.set({ name : 'hasChosenLength', value: 'true', date : { days : 365 }}) ;
      this.ajaxRequest('action=getLengthPop', {}, 'showpopup') ;
    }
    this.checkSubmit();
  },

  checkSubmit : function() {
    try {
      if ($('length').value > 0 && $('waist').value > 0) {
        $('begin').disabled = false ;
      }
    }catch(e){}
  },
  changeSize : function() {
    _w = (this.kilt == 8) ? this.lwaist : this.waist ;
    $param = { action : "getSizeForm", waist : _w, length : this.length }
    this.ajaxRequest($H($param).toQueryString(), {}, 'showpopup') ;
  },
  setNewSizes : function (_w, _l) {
    this.waist = _w ;
    this.length = _l ;
    if ((_w % 2) == 1) {
      this.lwaist = _w
    }else{
      this.lwaist = null ;
    }
    this.cancelNag(0) ;
    this.refreshCustomizerUi() ;
  },
  setLeatherWaist : function (_w) {
    this.lwaist = _w ;
    this.cancelNag(0) ;
    this.refreshCustomizerUi() ;
  },
  selectBeergut : function() {
    this.beergut = $('beergut').value ;
    $_params = $H({ action : 'getDesc',
      	              kilt : this.kilt,
      	             waist : this.waist,
      	            length : this.length,
                     color : this.color,
                   beergut : this.beergut }) ;
    this.ajaxRequest($_params.toQueryString(), {}, 'select_kilt') ;
  },

	ajaxRequest : function (_params, _ret, _callback, _method) {
	  Element.show('loader') ;
	  _method = (_method == undefined) ? "post" : _method ;
    _ret = (_ret == undefined) ? {} : _ret ;
    _callback = (_callback == undefined) ? null : _callback ;
    if (_ret['success'] == undefined) {
      var ajax = new Ajax.Request (
        this.ajaxurl,
  		  {
      		method      : _method,
      		evalScripts	: true,
      		onComplete	: function(request){Browse.performResponse(request, _callback)},
    		  onLoading	  : function(request){/*Element.show('loader') ;*/},
    		  parameters  : _params,
    		  onFailure   : function(request){Element.hide('loader') ;}
    		 }
    	);
    } else {
      var ajax = new Ajax.Updater(
        _ret,
        this.ajaxurl,
  		  {
      		method      : _method,
      		evalScripts	: true,
      		onComplete	: function(request){Browse.performResponse(request, _callback)},
    		  onLoading	  : function(request){Element.show('loader') ;},
    		  parameters  : _params,
    		  onFailure   : function(request){Element.hide('loader') ;}
    		 }
    	);
    }
  },

  performResponse : function(request, callback) {
    Element.hide('loader') ;
    switch (callback) {
      case "showpopup" :
        try {
        	Element.hide('waist'); // hide select box
        	Element.hide('length');// hide select box
        } catch(e){}
        this.popupNag(request.responseText) ;
        break ;
      case "apNotify" :
        this.popupNag(request.responseText) ;
        break ;
      case "checkNotify" :
        try {
          atts = eval('(' + request.responseText + ')') ;
          if (atts['error'] == "false") {
            $('sizer').innerHTML = atts['msg'] ;
          }else{
            $("notify_message").innerHTML = atts['msg'] ;
          }

        }catch(e){ }
        break ;
      case "select_kilt" :

        try {atts = eval('(' + request.responseText + ')') }catch(e){
          var win = window.open() ;
          win.document.write(request.responseText) ;
          win.close()
        } ;

        $H(atts).each(function(val) {
          var checkscript = val[0].split('_') ;
          if (checkscript[1] == 'script') {
            eval ("try { " + val.value + " }catch(e){}" ) ;
          }else{
            try { $(val.key).innerHTML = unescape(val.value) ; } catch(e){}
          }
        });
        Browse.checkLeatherWaist() ;
        break ;
      case "shopping_cart" :
        window.location="shopping_cart.php";
        break ;
      case "apSaveGiftCard" :
        try {
          var ret = eval('(' + request.responseText + ')') ;
          if (ret['error'] == "false") {
            document.location = 'shopping_cart.php' ;
          }else{

            var Err = null ;
            $H(ret).each( function(val) {
              if (val[0] != "error") {
                try { var pn = $(val[0]).parentNode ; }catch(e){ } ;
                try { pn.removeChild( $(val[0] + '_err' ) ) ; }catch(e){ } ;
                if (val[1] != 'correct') {
                  Err = Builder.node("div", { 'id' : val[0] + "_err", 'class' : "err" }, val[1] ) ;
                  pn.appendChild(Err) ;
                }
              }
            }) ;
          }
        } catch(e) {} ;
        break ;
    }
  },
  checkLeatherWaist : function() {
    if (this.kilt == "08") {
      if (!this.lwaist) {
        this.ajaxRequest('action=getLeatherWaist', {}, 'showpopup') ;
      }
    }
  },
  popupNag : function(_html) {
    $('popup_container').innerHTML = _html ;
    Element.show('popup_container') ;
  },
  cancelNag : function(_id) {
  	try {
      	Element.show('waist'); // hide select box
      	Element.show('length');// hide select box
      } catch(e){}
    Element.hide('popup_container') ;
    $('popup_container').innerHTML = '' ;
    switch (_id) {
      case '1' :
        this.ajaxRequest('action=getWaistPop2', {}, 'showpopup') ;
        break ;
    }
  },
  getNotify : function($products_id,$model,$waist,$length,$color,$beergut) {
    if (this.lwaist == null) this.lwaist = $waist ;
    var _send = $H({ products_id : $products_id,
                     model : $model,
                     waist : $waist,
                     lwaist : this.lwaist,
                     length : $length,
                     color : $color,
                    beergut : $beergut}).toQueryString() ;
    this.ajaxRequest('action=notifyMe&' + _send, {}, 'showpopup') ;
  },
  saveNotify : function() {
    var _send = $('notify_form').serialize();
    this.ajaxRequest(_send, {}, 'checkNotify' ) ;
  },

  refreshCustomizerUi : function() {
  	_param = { action : "getUI",
  	           kilt : this.kilt,
  	           waist : this.waist,
  	           lwaist : this.lwaist,
  	           length : this.length,
  	           color : this.color }
    this.ajaxRequest($H(_param).toQueryString(), { success : 'narrowColumn' }) ;
  },

/* SELECT KILT
=================================================================*/

  selectKilt : function( kilt_id ){
  	current_kilt = $( 'kilt_' + this.kilt );
  	Element.removeClassName( current_kilt , 'current');
  	Element.addClassName( 'kilt_' + kilt_id, 'current');
  	this.kilt = kilt_id ;
  	$_params = { action : 'getDesc',
  	             kilt : this.kilt,
  	             waist : this.waist,
  	             lwaist : this.lwaist,
  	             length : this.length,
                 color : this.color,
                 beergut : this.beergut} ;

  	this.ajaxRequest($H($_params).toQueryString(), {}, 'select_kilt') ;
  },


/* BUY KILT
=================================================================*/

  buyNow : function( product_id, kilt_id, waist, length, color, beergut ){

    $_params = {
      action : 'buyNow',
      products_id : product_id,
      model       : kilt_id,
      waist       : waist,
      length      : length,
      color       : color,
      beergut     : beergut } ;

    this.ajaxRequest($H($_params).toQueryString(), {}, 'shopping_cart') ;
  },

  getLeatherChop : function(_sku) {
    var t = $('leather_size') ;
    if (t[t.selectedIndex].value == "select") {
      alert("Select your desired length.") ;
    }else {
      $_params = { "action" : 'getKiltChop', "sku" : _sku, "chop_len" : t[t.selectedIndex].value } ;

      this.ajaxRequest($H($_params).toQueryString(), {}, 'shopping_cart') ;
    }


  },

/* BUY KILT W/CHOP
=================================================================*/

  getKiltChop : function( _sku ){

    $_params = { "action" : 'getKiltChop', "sku" : _sku, "chop_len" : this.length } ;

    this.ajaxRequest($H($_params).toQueryString(), {}, 'shopping_cart') ;
  },


/* PRODUCT NOTIFICATION
=================================================================*/

  selectColor : function( color ){
    currentColor = $('color_' + Browse.color) ;
    /* prev
    var _add = this.in_stock[Number(this.color)] > 0 ? 'cavail' : 'cunavail' ;
    Element.removeClassName( 'color_' + this.color , 'csel');
    Element.addClassName( 'color_' + this.color , _add);

    var _remove = this.in_stock[Number(color)] > 0 ? 'cavail' : 'cunavail' ;
  	Element.removeClassName( 'color_' + color , _remove);
  	Element.addClassName( 'color_' + color, 'csel');
    */
    Element.removeClassName( 'color_' + this.color , 'csel');
    Element.addClassName( 'color_' + color, 'csel');
  	this.color = color;
  	$_params = { action : 'getDescription',
  	             kilt : this.kilt,
  	             waist : this.waist,
  	             lwaist : this.lwaist,
  	             length : this.length,
                 color : this.color,
                 beergut: this.beergut } ;

  	this.ajaxRequest($H($_params).toQueryString(), {}, 'select_kilt') ;
  },

  selectColorAll : function( color ){
  	// get/set our Description
  	var ajax = new Ajax.Updater(
			{success: ''},
			this.ajaxurl,{
			method			: 'get',
			onComplete	: function( kilt_code ){
				hideLoader;
					var check =  false;
					var content = kilt_code.responseText;
					var splitter = content.split(',');
					for( i =0; i < splitter.length; i++ ){
						if(  splitter[i] == Browse.kilt ){
							check = true;
						}
				}
					if( check == true ){
						Browse.selectColor( color );
					} else {
						Browse.color = color;
						Browse.selectKilt( splitter[0] );
					}
				},
			evalScripts	: true,
			onLoading		: function() {Element.show('loader');},
			parameters	: 'action=selectColorAll&color=' + color,
			onFailure		: reportError});
  },
  /* Additional product methods
  ==============================================================*/
  apBuyNow : function(_att_flag, _model) {
    var ops = this.apGetData(_att_flag, _model, 'apBuyNow') ;
    this.ajaxRequest(ops.toQueryString(), {}, 'shopping_cart') ;
  },

  apSelectOption : function (_att_flag, _model) {
    var ops = this.apGetData(_att_flag, _model, 'apGetBuyNow') ;
    this.ap_chk = false ;
    ops.each( function(val) {
      Browse.ap_chk = (val[1] == 0) ? true : Browse.ap_chk ;
    });
    if (!this.ap_chk) {
      this.ap_chk = false ;
      this.ajaxRequest(ops.toQueryString(), { success : 'buy_now' }) ;
    }
  },
  apGetData : function (_att_flag, _model, _action) {
    switch (_att_flag) {
      case "belts" :
        var ops = $H({
            action : _action,
          att_flag : _att_flag,
             model : _model,
              size : $('size').value }) ;
        break ;
      case "tops" :
        var ops = $H({
            action : _action,
          att_flag : _att_flag,
             model : _model,
              size : $('size').value,
             color : $('color').value,
             slogan : $('slogan').value }) ;
        break ;
      case "other" :
        var ops = $H({
            action : _action,
          att_flag : _att_flag,
            model  : _model,
            custom : $('custom').value }) ;
        break ;
    }
    return ops ;
  },

  apNotify : function(_att_flag, _model) {
    var ops = this.apGetData(_att_flag, _model, 'apGetNotify' ) ;
    this.ajaxRequest(ops.toQueryString(), {}, 'apNotify') ;
  },
  apSaveNotify : function () {
    var ops = $('notify_form').serialize() ;
    this.ajaxRequest(ops, {}, 'checkNotify') ;
  },
  apConfigGiftCard : function() {
    Element.show('gc_config') ;
  },
  apSaveGiftCard : function() {
    this.ajaxurl = "pinfo.php"
    var ops = $('configure_form').serialize() ;
    this.ajaxRequest(ops, {}, 'apSaveGiftCard' ) ;
  }



};

Browse.init() ;

/* CUSTOMIZER
==============================================================*/

// when the user clicks "begin", we swap the UI
function showCustomizerUi( waist, length ){
	Browse.waist = waist;
	Browse.length = length;
	_parms = { action : 'getUI',
	           kilt : (Browse.kilt) ? Browse.kilt : '0',
	           color : Browse.color,
	           waist : Browse.waist,
	           length : Browse.length } ;

	new Ajax.Updater(
	{success: 'narrowColumn'},
	'customizer.php',{
	method			: 'get',
	onComplete	: function(){Element.hide("loader");},
	evalScripts	: true,
	onLoading		: function(){Element.show('loader');},
	parameters	: $H(_parms).toQueryString(),
	onFailure		: reportError});
}

function popupWindow(_url) {
  window.open(_url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=100,height=100,screenX=150,screenY=150,top=150,left=150') ;
}

