//jquery form
(function($){$.fn.ajaxSubmit=function(options){if(!this.length){log('ajaxSubmit: skipping submit process - no element selected');return this}if(typeof options=='function')options={success:options};var url=$.trim(this.attr('action'));if(url){url=(url.match(/^([^#]+)/)||[])[1]}url=url||window.location.href||'';options=$.extend({url:url,type:this.attr('method')||'GET',iframeSrc:/^https/i.test(window.location.href||'')?'javascript:false':'about:blank'},options||{});var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this}if(options.beforeSerialize&&options.beforeSerialize(this,options)===false){log('ajaxSubmit: submit aborted via beforeSerialize callback');return this}var a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;for(var n in options.data){if(options.data[n]instanceof Array){for(var k in options.data[n])a.push({name:n,value:options.data[n][k]})}else a.push({name:n,value:options.data[n]})}}if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this}this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this}var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null}else options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm()});if(options.clearForm)callbacks.push(function(){$form.clearForm()});if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){$(options.target).html(data).each(oldSuccess,arguments)})}else if(options.success)callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)callbacks[i].apply(options,[data,status,$form])};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)if(files[j])found=true;var multipart=false;if((files.length&&options.iframe!==false)||options.iframe||found||multipart){if(options.closeKeepAlive)$.get(options.closeKeepAlive,fileUpload);else fileUpload()}else $.ajax(options);this.trigger('form-submit-notify',[this,options]);return this;function fileUpload(){var form=$form[0];if($(':input[name=submit]',form).length){alert('Error: Form elements must not be named "submit".');return}var opts=$.extend({},$.ajaxSettings,options);var s=$.extend(true,{},$.extend(true,{},$.ajaxSettings),opts);var id='jqFormIO'+(new Date().getTime());var $io=$('<iframe id="'+id+'" name="'+id+'" src="'+opts.iframeSrc+'" />');var io=$io[0];$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={aborted:0,responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;$io.attr('src',opts.iframeSrc)}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&$.active--;return}if(xhr.aborted)return;var cbInvoked=0;var timedOut=0;var sub=form.clk;if(sub){var n=sub.name;if(n&&!sub.disabled){options.extraData=options.extraData||{};options.extraData[n]=sub.value;if(sub.type=="image"){options.extraData[name+'.x']=form.clk_x;options.extraData[name+'.y']=form.clk_y}}}setTimeout(function(){var t=$form.attr('target'),a=$form.attr('action');form.setAttribute('target',id);if(form.getAttribute('method')!='POST')form.setAttribute('method','POST');if(form.getAttribute('action')!=opts.url)form.setAttribute('action',opts.url);if(!options.skipEncodingOverride){$form.attr({encoding:'multipart/form-data',enctype:'multipart/form-data'})}if(opts.timeout)setTimeout(function(){timedOut=true;cb()},opts.timeout);var extraInputs=[];try{if(options.extraData)for(var n in options.extraData)extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);form.submit()}finally{form.setAttribute('action',a);t?form.setAttribute('target',t):$form.removeAttr('target');$(extraInputs).remove()}},10);var domCheckCount=50;function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;var isXml=opts.dataType=='xml'||doc.XMLDocument||$.isXMLDoc(doc);log('isXml='+isXml);if(!isXml&&(doc.body==null||doc.body.innerHTML=='')){if(--domCheckCount){cbInvoked=0;setTimeout(cb,100);return}log('Could not access iframe DOM after 50 tries.');return}xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;xhr.getResponseHeader=function(header){var headers={'content-type':opts.dataType};return headers[header]};if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];if(ta)xhr.responseText=ta.value;else{var pre=doc.getElementsByTagName('pre')[0];if(pre)xhr.responseText=pre.innerHTML}}else if(opts.dataType=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText)}data=$.httpData(xhr,opts.dataType)}catch(e){ok=false;$.handleError(opts,xhr,'error',e)}if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts])}if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null},100)};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s)}else doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null}}};$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().bind('submit.form-plugin',function(){$(this).ajaxSubmit(options);return false}).bind('click.form-plugin',function(e){var target=e.target;var $el=$(target);if(!($el.is(":submit,input:image"))){var t=$el.closest(':submit');if(t.length==0)return;target=t[0]}var form=this;form.clk=target;if(target.type=='image'){if(e.offsetX!=undefined){form.clk_x=e.offsetX;form.clk_y=e.offsetY}else if(typeof $.fn.offset=='function'){var offset=$el.offset();form.clk_x=e.pageX-offset.left;form.clk_y=e.pageY-offset.top}else{form.clk_x=e.pageX-target.offsetLeft;form.clk_y=e.pageY-target.offsetTop}}setTimeout(function(){form.clk=form.clk_x=form.clk_y=null},100)})};$.fn.ajaxFormUnbind=function(){return this.unbind('submit.form-plugin click.form-plugin')};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el){a.push({name:n,value:$(el).val()});a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y})}continue}var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)a.push({name:n,value:v[j]})}else if(v!==null&&typeof v!='undefined')a.push({name:n,value:v})}if(!semantic&&form.clk){var $input=$(form.clk),input=$input[0],n=input.name;if(n&&!input.disabled&&input.type=='image'){a.push({name:n,value:$input.val()});a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y})}}return a};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic))};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)a.push({name:n,value:v[i]})}else if(v!==null&&typeof v!='undefined')a.push({name:this.name,value:v})});return $.param(a)};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))continue;v.constructor==Array?$.merge(val,v):val.push(v)}return val};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=op.value;if(!v)v=(op.attributes&&op.attributes['value']&&!(op.attributes['value'].specified))?op.text:op.value;if(one)return v;a.push(v)}}return a}return el.value};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields()})};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')this.value='';else if(t=='checkbox'||t=='radio')this.checked=false;else if(tag=='select')this.selectedIndex=-1})};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))this.reset()})};$.fn.enable=function(b){if(b==undefined)b=true;return this.each(function(){this.disabled=!b})};$.fn.selected=function(select){if(select==undefined)select=true;return this.each(function(){var t=this.type;if(t=='checkbox'||t=='radio')this.checked=select;else if(this.tagName.toLowerCase()=='option'){var $sel=$(this).parent('select');if(select&&$sel[0]&&$sel[0].type=='select-one'){$sel.find('option').selected(false)}this.selected=select}})};function log(){if($.fn.ajaxSubmit.debug&&window.console&&window.console.log)window.console.log('[jquery.form] '+Array.prototype.join.call(arguments,''))}})(jQuery);
function check_shopping_cart() {

  var test=location.href;
  var matchPos1 = test.search("checkout.php");
  if (matchPos1!= -1) {
	  
	  return true;
  }
  else {
return false;
  }
}
function check_prod_info() {

  var test2=location.href;
  var matchPos2 = test2.search("product_info");
  if (matchPos2!= -1) {
	  
	  return true;
  }
  else {
return false;
  }
}	
	
	$(document).ready(function(){	
	//if (check_prod_info==false){
	//	$("#descriere_produs").onselectstart = function() { return false; }
	//	$("#descriere_produs").oncontextmenu = function() { return false; }
//		$("#descriere_produs").ondragstart = function() { return false; }
//	}
				$("#slider").easySlider({
				auto: true, 
				continuous: true
				
			});
				
				$("#txtSearch").attr ("autocomplete","off");
				$('#txtSearch').searchlight('searchsuggest.php');
				$('a[rel*=facebox]').facebox({
        loading_image : "images/icons/facebox/loading.gif",
        close_image   : "images/icons/facebox/closelabel.gif",
		opacity : 0.4,
		modal : true
		    });
				var hideDelay = 500;    
  var currentID;  
  var hideTimer = null;  
  
  // One instance that's reused to show info for the current person  
  var container = $('<div id="personPopupContainer">'  
      + '<table width="" border="0" cellspacing="0" cellpadding="0" align="center" class="tipDiv" id="tipDiv">'  
      + '<tr>'  
      + '   <td class="corner topLeft"></td>'  
      + '   <td class="top"></td>'  
      + '   <td class="corner topRight"></td>'  
      + '</tr>'  
      + '<tr>'  
      + '   <td class="left">&nbsp;</td>'  
      + '   <td><div id="personPopupContent"></div></td>'  
      + '   <td class="right">&nbsp;</td>'  
      + '</tr>'  
      + '<tr>'  
      + '   <td class="corner bottomLeft">&nbsp;</td>'  
      + '   <td class="bottom">&nbsp;</td>'  
      + '   <td class="corner bottomRight"></td>'  
      + '</tr>'  
      + '</table>'  
      + '</div>');  
  
  $('body').append(container);  
  
  $('.personPopupTrigger').live('mouseover', function()  
  {  
        var settings = $(this).attr('rel');
	   if (settings == '')  
          return; 
		  
	  if (hideTimer)  
          clearTimeout(hideTimer);  
 
		  
      var pos = $(this).offset();  
      var width = $(this).width();  
   container.css({  
          left: (pos.left - width) -145+ 'px',  
          top: pos.top - 15 + 'px'  
      });  
   
  var url='';
      $('#personPopupContent').html('Asteptati pana se incarca...');  
  
      $.ajax({  
          type: 'GET',  
          data: settings,  
         // data: 'popup_add_det.php?products_id='+settings,  
		 url: 'popup_add_det.php?products_id='+settings,
		    //   data: 'page=' + pageID + '&guid=' + currentID,  
          success: function(url)  
          {  
				 $('#personPopupContent').html(url);  
          }  
      });  
    
      container.css('display', 'block');  
	  
  });  
  
  $('.personPopupTrigger').live('mouseout', function()  
  {  
      if (hideTimer)  
          clearTimeout(hideTimer);  
      hideTimer = setTimeout(function()  
      {  
          container.css('display', 'none');  
      }, hideDelay);  
  });  
  
  // Allow mouse over of details without hiding details  
  $('#personPopupContainer').mouseover(function()  
  {  
      if (hideTimer)  
          clearTimeout(hideTimer);  
  });  
  
  // Hide after mouseout  
  $('#personPopupContainer').mouseout(function()  
  {  
      if (hideTimer)  
          clearTimeout(hideTimer);  
      hideTimer = setTimeout(function()  
      {  
          container.css('display', 'none');  
      }, hideDelay);  
  }); 
  
	
		});	

/***********************************************
* Cross browser Marquee II- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=2 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?

////NO NEED TO EDIT BELOW THIS LINE////////////

var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''

function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}

function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("marqueecontainer").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}

if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
if (check_shopping_cart==false) {
window.attachEvent("onload", initializemarquee)}
else if (document.getElementById)if (check_shopping_cart==false) {
window.onload=initializemarquee}


 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')
}



function change_cart(v,f)
{
 document.getElementById("cart_price").innerHTML =  Math.round(v*f*100)/100;
 
 }



(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
        .click(function() {if ($.facebox.settings.modal != true) $(document).trigger('close.facebox')}) 
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);


(function($) {
    var SearchLight = function(input, url, options) {
        settings = $.extend({
            minimumCharacters: 2,
			zIndex: 300,
			autocomplete: "off",
            searchDelay: 1,
            limitPerCategory: 5,
            actionFunction: null,
            align: 'left',
            width: 'auto',
            showIcons: true,
            showEffect: 'fade', // TODO
            hideEffect: 'fade'  // TODO
        }, options);
        this._settings = settings;
		var input = $(input);
		input.attr("autocomplete", "off");
		var container = $(document.createElement('div'));
        container.attr('className',  'searchlight-balloon');
        container.css({
            position: 'absolute',
            top: input.offset().top + input.outerHeight(),
            display: 'none'
        });

        if (settings.width == 'auto') {
            container.css('width', input.outerWidth());
        }
        if (settings.align == 'left') {
            container.css('left', input.offset().left);
        } else if (settings.align == 'right') {
            container.css('right', $(document.body).innerWidth() - (input.offset().left + input.outerWidth()));
        }

        var results = $(document.createElement('div'));
        results.attr('className', 'searchlight-results-wrapper');
        results.css({
            height: '100%'
        });

        if ($.browser.msie && parseFloat($.browser.version) <= 7) {
            results.css({
                width: '1%'
            });
        }

        container.append(results);
        $(document.body).append(container);


        this._input = input;
        this._container = container;
        this._searchURL = url;
        this._resultsContainer = results;

        input.bind('focus.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;
            if (this.value.length >= settings.minimumCharacters) {
                searchlight.search(this.value);
            }
        });
        $(document.body).bind('mousedown.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;

            // Make sure we didn't click the searchlight
            var node = evt.target;
            var c = 0
            while (node) {
                // Clicked searchlight, so return
                if (node == searchlight._input[0] || node == searchlight._container[0]) {
                    return;
                }
                node = node.parentNode;
            }

            searchlight.hide();
        });

        input.bind('keydown.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;
            if (evt.which == 38 && searchlight._selectedRow > -1) {
                // Up arrow
                searchlight.selectRow(searchlight._selectedRow-1);
            } else if (evt.which == 40 && searchlight._selectedRow < searchlight._rowCount -1) {
                // Down arrow
                searchlight.selectRow(searchlight._selectedRow+1);
            } else if (evt.which == 13 && searchlight._selectedRow > -1) {
                searchlight.activateRow(searchlight._selectedRow);
				evt.preventDefault();
            }
             if (evt.which == 38 || evt.which == 40) {
                evt.preventDefault();
            }
			if (evt.which == 13 && searchlight._selectedRow == -1) {
                searchlight.activateRow(searchlight._selectedRow);
				
            }
			
        });
        input.bind('keyup.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;
            if (searchlight._searchDelayTimer) {
                clearTimeout(searchlight._searchDelayTimer);
            }
            searchlight._searchDelayTimer = setTimeout(function() {
                var input = searchlight._input[0];
                if (input.value == searchlight._previousQuery) {
                } else if (input.value.length >= settings.minimumCharacters) {
                    searchlight.search(input.value);
                } else {
                    searchlight.hide();
                }
            }, settings.searchDelay);
        });
        input.bind('keypress.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;
        });
        this._container.bind('mouseleave.searchlight', {searchlight: this}, function(evt) {
            var searchlight = evt.data.searchlight;
            searchlight.selectRow(-1);
        });


        this.resultAction = settings.actionFunction ? settings.actionFunction : this.defaultResultAction;
    };
    SearchLight.prototype.show = function() {
        if (!this._container.is(':visible')) {
            this._container.fadeIn('fast');
        }
    };
    SearchLight.prototype.hide = function() {
        if (this._disableHide) {
            return;
        }
        this._container.fadeOut('fast');
    };
    SearchLight.prototype.search = function(query) {
        var searchlight = this;
        this._previousQuery = query;
        if (this._previousXHR) {
            this._previousXHR.abort();
        }
        this._previousXHR = $.getJSON(this._searchURL, {q: query}, function(results) {
            searchlight.clearResults();
            for (var i = 0; i < results.length; i++) {
                var r = results[i]
                if (r.results.length > 0) {
                    searchlight.addResultCategory(r.title, r.results);
                }
            }
            searchlight.show();
        });
    };
    SearchLight.prototype.clearResults = function() {
        this._categoryCount = 0;
        this._rowCount = 0;
        this._selectedRow = -1;
        this._resultsContainer.html('<table class="searchlight-results"></table>');
    };
    SearchLight.prototype.addResultCategory = function(name, results) {
        var first = true;
        for (var i = 0; i < results.length; i++) {
            var r = results[i];

            var tr = document.createElement('tr');
            $(tr).attr('className', 'searchlight-not-selected');

            var th = document.createElement('th');
            var td = document.createElement('td');
            $(th).html('<span class="searchlight-header-text"></span>');
            $(td).html('<span class="searchlight-result-text"></span>');
            var th_d = th.firstChild;
            var td_d = td.firstChild;

            if (first) {
                $(th_d).text(name);
                first = false;
            }

            if (this._settings.showIcons) {
                var img = document.createElement('img');
                img.className = 'searchlight-result-icon';
                img.style.width = '20px';
                img.style.height = '20px';
                // If icon, then use that otherwise use blank
                img.src = r[2] ? r[2] : '';
                $(td_d).append(img);
            }

            $(td_d).append(r[1]);

            $(tr).append(th);
            $(tr).append(td);

            $(tr).bind('mousemove', {searchlight: this}, function(evt) {
                var searchlight = evt.data.searchlight;
                searchlight.selectRow(this._rowId);
            });
            $(tr).bind('click', {searchlight: this}, function(evt) {
                var searchlight = evt.data.searchlight;
                searchlight.activateRow(this._rowId);
            });

            tr._rowId = this._rowCount;
            tr._actionValue = r[0];
            this._resultsContainer.children('table').append(tr);
            this._rowCount++;
        }

        // Add spacer if this isn't the first category
        var tr = document.createElement('tr');
        var th = document.createElement('th');
        var td = document.createElement('td');
        tr.className = 'searchlight-spacer-row';

        $(tr).append(th);
        $(tr).append(td);
        this._resultsContainer.children('table').append(tr);

        this._categoryCount++;
    };

    SearchLight.prototype.selectRow = function(id) {
        this._selectedRow = id;

        this._resultsContainer.find('tr:not(.searchlight-spacer-row)').each(function(i) {
            if (this._rowId == id) {
                if (!$(this).hasClass('searchlight-selected')) {
                    $(this).removeClass('searchlight-not-selected');
                    $(this).addClass('searchlight-selected');
                }
            } else {
                if (!$(this).hasClass('searchlight-not-selected')) {
                    $(this).removeClass('searchlight-selected');
                    $(this).addClass('searchlight-not-selected');
                }
            }
        });
    };

    SearchLight.prototype.activateRow = function(id) {
        this.resultAction(this._resultsContainer.find('tr:not(.searchlight-spacer-row):eq('+ id +')')[0]._actionValue);
    }

    SearchLight.prototype.defaultResultAction = function(val) {
        window.location.href = val;
    };


    $.fn.searchlight = function(url, options) {
        this.each(function() {
            new SearchLight(this, url, options);
        });
    };
})(jQuery);

(function($) {

	$.fn.easySlider = function(options){
	  
		// default configuration properties
		var defaults = {			
			prevId: 		'prevBtn',
			prevText: 		'Previous',
			nextId: 		'nextBtn',	
			nextText: 		'Next',
			controlsShow:	true,
			controlsBefore:	'',
			controlsAfter:	'',	
			controlsFade:	true,
			firstId: 		'firstBtn',
			firstText: 		'First',
			firstShow:		false,
			lastId: 		'lastBtn',	
			lastText: 		'Last',
			lastShow:		false,				
			vertical:		false,
			speed: 			600,
			auto:			true,
			pause:			2000,
			continuous:		false, 
			numeric: 		true,
			numericId: 		'controls'
			
		}; 
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {  
			var obj = $(this); 				
			var s = $("li", obj).length;
			var w = $("li", obj).width(); 
			var h = $("li", obj).height(); 
			var clickable = true;
			obj.width(w); 
			obj.height(h); 
			
			obj.css("overflow","hidden");
			var ts = s-1;
			var t = 0;
			$("ul", obj).css('width',s*w);			
			
			if(options.continuous){
				$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
				$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
				$("ul", obj).css('width',(s+1)*w);
			};				
			
			if(!options.vertical) $("li", obj).css('float','left');
								
			if(options.controlsShow){
				var html = options.controlsBefore;				
				if(options.numeric){
					html += '<ol id="'+ options.numericId +'"></ol>';
				} else {
					if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
					html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
					html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
					if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';				
				};
				
				html += options.controlsAfter;						
				$(obj).after(html);										
			};
			
			if(options.numeric){									
				for(var i=0;i<s;i++){						
					$(document.createElement("li"))
						.attr('id',options.numericId + (i+1))
						.html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>')
						.appendTo($("#"+ options.numericId))
						.click(function(){							
							animate($("a",$(this)).attr('rel'),true);
						}); 												
				};							
			} else {
				$("a","#"+options.nextId).click(function(){		
					animate("next",true);
				});
				$("a","#"+options.prevId).click(function(){		
					animate("prev",true);				
				});	
				$("a","#"+options.firstId).click(function(){		
					animate("first",true);
				});				
				$("a","#"+options.lastId).click(function(){		
					animate("last",true);				
				});				
			};
			
			function setCurrent(i){
				i = parseInt(i)+1;
				$("li", "#" + options.numericId).removeClass("current");
				$("li#" + options.numericId + i).addClass("current");
			};
			
			function adjust(){
				if(t>ts) t=0;		
				if(t<0) t=ts;	
				if(!options.vertical) {
					$("ul",obj).css("margin-left",(t*w*-1));
				} else {
					$("ul",obj).css("margin-left",(t*h*-1));
				}
				clickable = true;
				if(options.numeric) setCurrent(t);
			};
			
			function animate(dir,clicked){
				if (clickable){
					clickable = false;
					var ot = t;				
					switch(dir){
						case "next":
							t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;						
							break; 
						case "prev":
							t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
							break; 
						case "first":
							t = 0;
							break; 
						case "last":
							t = ts;
							break; 
						default:
							t = dir;
							break; 
					};	
					var diff = Math.abs(ot-t);
					var speed = diff*options.speed;						
					if(!options.vertical) {
						p = (t*w*-1);
						$("ul",obj).animate(
							{ marginLeft: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);				
					} else {
						p = (t*h*-1);
						$("ul",obj).animate(
							{ marginTop: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);					
					};
					
					if(!options.continuous && options.controlsFade){					
						if(t==ts){
							$("a","#"+options.nextId).hide();
							$("a","#"+options.lastId).hide();
						} else {
							$("a","#"+options.nextId).show();
							$("a","#"+options.lastId).show();					
						};
						if(t==0){
							$("a","#"+options.prevId).hide();
							$("a","#"+options.firstId).hide();
						} else {
							$("a","#"+options.prevId).show();
							$("a","#"+options.firstId).show();
						};					
					};				
					
					if(clicked) clearTimeout(timeout);
					if(options.auto && dir=="next" && !clicked){;
						timeout = setTimeout(function(){
							animate("next",false);
						},diff*options.speed+options.pause);
					};
			
				};
				
			};
			// init
			var timeout;
			if(options.auto){;
				timeout = setTimeout(function(){
					animate("next",false);
				},options.pause);
			};		
			
			if(options.numeric) setCurrent(0);
		
			if(!options.continuous && options.controlsFade){					
				$("a","#"+options.prevId).hide();
				$("a","#"+options.firstId).hide();				
			};				
			
		});
	  
	};

})(jQuery);





///// AJAX SHOPPING CART

SHOW_ADDED = 1; // set 0 if you no need show
Offset_X = -10;
Offset_Y = -30;
/**
 * Subsys_JsHttpRequest_Js: JavaScript DHTML data loader.
 * (C) 2005 Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * See http://www.gnu.org/copyleft/lesser.html
 *
 * Do not remove this comment if you want to use script!
 * Не удаляйте данный комментарий, если вы хотите использовать скрипт!
 *
 * This library tries to use XMLHttpRequest (if available), and on
 * failure - use dynamically created <script> elements. Backend code
 * is the same for both cases.
 *
 * @author Dmitry Koterov
 * @version 3.29
 */

function Subsys_JsHttpRequest_Js() { this._construct() }
(function() { // to create local-scope variables
    var COUNT       = 0;
    var PENDING     = {};
    var CACHE       = {};

    // Called by server script on data load.
    Subsys_JsHttpRequest_Js.dataReady = function(id, text, js) {
        var undef;
        var th = PENDING[id];
        delete PENDING[id];
        if (th) {
            delete th._xmlReq;
            if (th.caching) CACHE[th.hash] = [text, js];
            th._dataReady(text, js);
        } else if (typeof(th) != typeof(undef)) {
            alert("ScriptLoader: unknown pending id: "+id);
        }
    }

    Subsys_JsHttpRequest_Js.prototype = {
        // Standard properties.
        onreadystatechange: null,
        readyState:         0,
        responseText:       null,
        responseXML:        null,
        status:             200,
        statusText:         "OK",

        // Additional properties.
        session_name:       "osCsid",  // set to SID cookie or GET parameter name
        responseJS:         null,         // JavaScript response array/hash
        caching:            false,        // need to use caching?

        // Internals.
        _span:              null,
        _id:                null,
        _xmlReq:            null,
        _openArg:           null,
        _reqHeaders:        null,

        dummy: function() {}, // empty function

        abort: function() {
            if (this._xmlReq) return this._xmlReq.abort();
            if (this._span) {
                this.readyState = 0;
                if (this.onreadystatechange) this.onreadystatechange();
                this._cleanupScript();
            }
        },

        open: function(method, url, asyncFlag, username, password) {
            this._openArg = {
                'method':    method,
                'url':       url,
                'asyncFlag': asyncFlag,
                'username':  username,
                'password':  password
            };
            this._id = null;
            this._xmlReq = null;
            this._reqHeaders = [];
            return true;
        },

        send: function(content) {
            var id = (new Date().getTime()) + "" + COUNT++;

            // Build QUERY_STRING from query hash.
            var query = this._hash2query(content);

            // Append SID to original URL now.
            var url = this._openArg.url;
            var sid = this._getSid();
            if (sid) url += (url.indexOf('?')>=0? '&' : '?') + this.session_name + "=" + this.escape(sid);

            // Solve hash BEFORE appending ID.
            var hash = this.hash = url + '?' + query;
            if (this.caching && CACHE[hash]) {
                var c = CACHE[hash];
                this._dataReady(c[0], c[1]);
                return false;
            }

            // Try to use XMLHttpRequest.
            this._xmlReq = this._obtainXmlReq(id, url);

            // Pass data in URL (GET, HEAD etc.) or in request body (POST)?
            var hasSetHeader = this._xmlReq && (window.ActiveXObject || this._xmlReq.setRequestHeader);
            var href, body;
            if (this._xmlReq && hasSetHeader && (""+this._openArg.method).toUpperCase() == "POST") {
                // Use POST method. Pass query in request body.
                // Opera 8.01 does not support setRequestHeader, so no POST method.
                this._openArg.method = "POST";
                href = url;
                body = query;
            } else {
                this._openArg.method = "GET";
                href = url + (url.indexOf('?')>=0? '&' : '?') + query;
                body = null;
            }

            // Append ID: a=aaa&b=bbb&<id>
            href = href + (href.indexOf('?')>=0? '&' : '?') + id;

            // Save loading script.
            PENDING[id] = this;

            if (this._xmlReq) {
                // Open request now & send it.
                // In XMLHttpRequest mode request URL MUST be ended with "<id>-xml".
                var a = this._openArg;
                this._xmlReq.open(a.method, href+"-xml", a.asyncFlag, a.username, a.password);
                if (hasSetHeader) {
                    // Pass pending headers.
                    for (var i=0; i<this._reqHeaders.length; i++)
                        this._xmlReq.setRequestHeader(this._reqHeaders[i][0], this._reqHeaders[i][1]);
                    // Set non-default Content-type. We cannot use
                    // "application/x-www-form-urlencoded" here, because
                    // in PHP variable HTTP_RAW_POST_DATA is accessible only when
                    // enctype is not default (e.g., "application/octet-stream"
                    // is a good start). We parse POST data manually in backend
                    // library code.
                    this._xmlReq.setRequestHeader('Content-Type', 'application/octet-stream');
                }
                // Send the request.
                return this._xmlReq.send(body);
            } else {
                // Create <script> element and run it.
                this._obtainScript(id, href);
                return true;
            }
        },

        getAllResponseHeaders: function() {
            if (this._xmlReq) return this._xmlReq.getAllResponseHeaders();
            return '';
        },

        getResponseHeader: function(label) {
            if (this._xmlReq) return this._xmlReq.getResponseHeader(label);
            return '';
        },

        setRequestHeader: function(label, value) {
            // Collect headers.
            this._reqHeaders[this._reqHeaders.length] = [label, value];
        },


        //
        // Internal functions.
        //

        // Constructor.
        _construct: function() {},

        // Do all work when data is ready.
        _dataReady: function(text, js) { with (this) {
            if (text !== null || js !== null) {
                readyState = 4;
                responseText = responseXML = text;
                responseJS = js;
            } else {
                readyState = 0;
                responseText = responseXML = responseJS = null;
            }
            if (onreadystatechange) onreadystatechange();
            _cleanupScript();
        }},

        // Create new XMLHttpRequest object.
        _obtainXmlReq: function(id, url) {
            // If url.domain specified, cannot use XMLHttpRequest!
            // XMLHttpRequest (and MS ActiveX'es) cannot work with different domains.
            if (url.match(new RegExp('^[a-z]+://', 'i'))) return null;

            // Try to use built-in loaders.
            var req = null;
            if (window.XMLHttpRequest) {
                try { req = new XMLHttpRequest() } catch(e) {}
            } else if (window.ActiveXObject) {
                try { req = new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
                if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
            }
            if (req) {
                var th = this;
                req.onreadystatechange = function() {
                    var s = req.readyState;
                    if (s == 4) {
                        // Avoid memory leak by removing closure.
                        req.onreadystatechange = th.dummy;
                        // Remove possible junk from response.
                        var responseText = req.responseText;
                        try {
                            // Call associated dataReady().
                            eval(responseText);
                        } catch (e) {
                            Subsys_JsHttpRequest_Js.dataReady(id, "JavaScript code generated by backend is invalid!\n"+responseText, null);
                        }
                    } else {
                        th.readyState = s;
                        if (th.onreadystatechange) th.onreadystatechange()
                    }
                };
                this._id = id;
            }
            return req;
        },

        // Create new script element and start loading.
        _obtainScript: function(id, href) { with (document) {
            var span = null;
            // Oh shit! Damned stupid fucked Opera 7.23 does not allow to create SCRIPT
            // element over createElement (in HEAD or BODY section or in nested SPAN -
            // no matter): it is created deadly, and does not respons on href assignment.
            // So - always create SPAN.
            span = body.appendChild(createElement("SPAN"));
            span.style.display = 'none';
            span.innerHTML = 'Text for stupid IE.<s'+'cript></' + 'script>';
            setTimeout(function() {
                var s = span.getElementsByTagName("script")[0];
                s.language = "JavaScript";
                if (s.setAttribute) s.setAttribute('src', href); else s.src = href;
            }, 10);
            this._id = id;
            this._span = span;
        }},

        // Remove last used script element (clean memory).
        _cleanupScript: function() {
            var span = this._span;
            if (span) {
                this._span = null;
                setTimeout(function() {
                    // without setTimeout - crash in IE 5.0!
                    span.parentNode.removeChild(span);
                }, 50);
            }
            return false;
        },

        // Convert hash to QUERY_STRING.
        _hash2query: function(content, prefix) {
            if (prefix == null) prefix = "";
            var query = [];
            if (content instanceof Object) {
                for (var k in content) {
                    var v = content[k];
                    if (v == null || ((v.constructor||{}).prototype||{})[k]) continue;
                    var curPrefix = prefix? prefix+'['+this.escape(k)+']' : this.escape(k);
                    if (v instanceof Object)
                        query[query.length] = this._hash2query(v, curPrefix);
                    else
                        query[query.length] = curPrefix + "=" + this.escape(v);
                }
            } else {
                query = [content];
            }
            return query.join('&');
        },

        // Return value of SID based on QUERY_STRING or cookie
        // (PHP compatible sessions).
        _getSid: function() {
            var m = document.location.search.match(new RegExp('[&?]'+this.session_name+'=([^&?]*)'));
            var sid = null;
            if (m) {
                sid = m[1];
            } else {
                var m = document.cookie.match(new RegExp(s='(;|^)\\s*'+this.session_name+'=([^;]*)'));
                if (m) sid = m[2];
            }
            return sid;
        },

        // Stupid JS escape() does not quote '+'.
        escape: function(s) {
            return escape(s).replace(new RegExp('\\+','g'), '%2B');
        }
    }
})();
function addHandler(object, event, handler) { // Thanks xpoint.ru!
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof object.attachEvent != 'undefined')
    object.attachEvent('on' + event, handler);
  else {
    var handlersProp = '_handlerStack_' + event;
    var eventProp = 'on' + event;
    if (typeof object[handlersProp] == 'undefined') {
      object[handlersProp] = [];
      if (typeof object[eventProp] != 'undefined')
        object[handlersProp].push(object[eventProp]);
      object[eventProp] = function(e) {
        var ret = true;
        for (var i = 0; ret != false && i < object[handlersProp].length; i++)
          ret = object[handlersProp][i](e);
        return ret;
    } }
    object[handlersProp].push(handler);
} }
function removeHandler(object, event, handler) { // Thanks xpoint.ru!
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);
  else {
    var handlersProp = '_handlerStack_' + event;
    if (typeof object[handlersProp] != 'undefined') {
      for (var i = 0; i < object[handlersProp].length; i++) {
        if (object[handlersProp][i] == handler) {
          object[handlersProp].splice(i, 1);
          return;
} } } } }
/**
  AJAXBuyNow v2.0

  author Weretennikoff Andrew aka Medreces medreces@yandex.ru

  Released under the GNU General Public License
*/
var x, y;
var loadingImage = new Image();
var okImage = new Image();
loadingImage.src = "images/loading.gif";
okImage.src = "images/ok.gif";

if (window.opera || (navigator.userAgent.indexOf('MSIE') > -1)) { //IE + Opera
  getM_x = function () { return event.clientX + document.body.scrollLeft; }
  getM_y = function () { return event.clientY + document.body.scrollTop; }
} else { // Mozilla
  addHandler(document, 'mousemove', function(e) {
    x = e.pageX;
    y = e.pageY;
  });
  getM_x = function () { return x; }
  getM_y = function () { return y; }
}
function showOk() {
  var imgLoading = document.getElementById("_loading_");
  with (imgLoading) {
    src = okImage.src;
    style.visibility = "visible";
} }

function hideOk() {
  if(document.getElementById("_loading_")) document.getElementById('_loading_').style.visibility = "hidden";
  removeHandler(document, 'mousemove', hideOk);
}
function showLoading() {
  var imgLoading = document.getElementById("_loading_");
  if(!imgLoading) {
    imgLoading = document.createElement("img");
    with(imgLoading) {
      id = "_loading_";
      style.position = "absolute";
      style.visibility = "hidden";
    }
    document.body.appendChild(imgLoading);
  }
  with(imgLoading) {
    src = loadingImage.src;
    style.left = (getM_x() + Offset_X) + "px";
    style.top = (getM_y() + Offset_Y) + "px";
    style.visibility = "visible";
} }
function hideLoading() {
  if(document.getElementById("_loading_")) document.getElementById("_loading_").style.visibility = "hidden";
}

function doBuyNowGet( link ) {
  showLoading();
  var params = {};


    var parts = link.split('&');

    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }


// Now you can get the parameters you want like so:
var products_id = params.products_id;
  var reqAddCart = new Subsys_JsHttpRequest_Js();
  reqAddCart.onreadystatechange = function() {
    if (reqAddCart.readyState == 4) {
      if (reqAddCart.responseJS) {
        document.location.href = reqAddCart.responseJS.ajax_redirect;
        return;
      }
      else {
        document.getElementById('divShoppingCard').innerHTML = '<table border="0" width="100%" cellspacing="0" cellpadding="2">'+(reqAddCart.responseText||'')+'</table>';
        hideLoading();
        if ( SHOW_ADDED ) {
          showOk();
           timerID = setTimeout( "addHandler(document, \'mousemove\', hideOk)", 500);
		//  jQuery.facebox({ajax: 'popup_add_success.php?products_id='+products_id});
        }
      }
    }
  }
  reqAddCart.caching = false;
  reqAddCart.open('GET', link, true);
  reqAddCart.send(null);
}

function doAddProduct(form) {
 showLoading();
  var reqAddCart = new Subsys_JsHttpRequest_Js();
    var senddata = new Object();
  var fe = form.elements;
    for(var i=0 ; i<fe.length ; i++) {
    if ( fe[i].type=="radio" || fe[i].type=="checkbox" ) {
      if ( fe[i].checked ) senddata[fe[i].name] = fe[i].value;
    } else {
      senddata[fe[i].name] = fe[i].value;
    }
  }
  var test=location.href;
  var matchPos1 = test.search("checkout.php");
  if (matchPos1!= -1) {
	  
	   var url = 'ajax_shopping_checkout.php?' + ( senddata.products_id ? 'products_id='+senddata.products_id+'&' : "" ) + 
  'action=add_product_to';
  }
  else {
  var url = 'ajax_shopping_cart.php?' + ( senddata.products_id ? 'products_id='+senddata.products_id+'&' : "" ) + 
  'action=add_product_to';
  }
  
  reqAddCart.onreadystatechange = function() {
    if (reqAddCart.readyState == 4) {
      if (reqAddCart.responseJS) {
        document.location.href = reqAddCart.responseJS.ajax_redirect;

        return;
      }
      else {
   document.getElementById('divShoppingCard').innerHTML = '<table width="100%">'+(reqAddCart.responseText||'')+'</table>';
        if (SHOW_ADDED ) {
          showOk();
		  
          timerID = setTimeout( "addHandler(document, \'mousemove\', hideOk)", 500);
		  //document.getElementById('personPopupContent').innerHTML='';
		   if (matchPos1!= -1) { 
		 }
		 else {
			 //jQuery.facebox({ajax: 'popup_add_success.php?products_id='+senddata.products_id});
			 }
        }
      }
    }
  }
// собираем все элементы формы:



  reqAddCart.caching = false;
  reqAddCart.open(form.method, url, true);
  reqAddCart.send(senddata);
 // alert (senddata[qty]);
 // jQuery.facebox({ajax: 'popup_add_success.php'});  
 // alert (url);
}
///// AJAX SHOPPING CART


