function addEvent( object, eventName, functionPtr )
{
if( window.addEventListener )
  object.addEventListener( eventName, functionPtr, false );
else if( window.attachEvent )
  object.attachEvent( "on" + eventName, functionPtr );
}

function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }
    alert(out);
}

// Ajax Callback functions
function donothing(response){}
function cartupdate(response)
{
    jresponse = JSON.parse(response);
    $('#'+jresponse.linetotalid).html(jresponse.linetotal);
    $('#carttotal').html(jresponse.carttotal.toFixed(2));
    sidecart(response);
    if(jresponse.carttotal)
    	$('#checkout_button').css('display','block');
    else
    	$('#checkout_button').css('display','none');
}
function sidecart(response)
{
    var response = JSON.parse(response);
    $('#sc_content').html(response.sidecart);
    $('#sidecartship').html(response.shipping);
    $('#adsense').html(response.adsense);
    
    if(response.carttotal)
    	$('#checkout_button').css('display','block');
    else
    	$('#checkout_button').css('display','none');
	
}
function sidebarshipping(response)
{
	$('#sidecartship').html(response);
}

function expanded(response)
{
	response = JSON.parse(response);
	$('#'+response.id).fadeOut(600,function(){$('#'+response.id).html(response.html);});
	$('#'+response.id).fadeIn(600);
}

//threadsafe asynchronous XMLHTTPRequest code
function ajaxSend(url,callback,parameters)
{
    function ajaxBindCallback()
    {
        if (ajaxRequest.readyState == 4)
        {
        	//alert(ajaxRequest.responseText+" "+ajaxRequest.status);
            if (ajaxRequest.status == 200)
            {
            	//alert(ajaxRequest.responseText);
                callback(ajaxRequest.responseText);
            }
            else
            {
                //alert("There was a problem retrieving the xml data:" + url +" " + ajaxRequest.status + ":\t" + ajaxRequest.statusText + ajaxRequest.responseText);
            }
        }
    }

  // use a local variable to hold our request and callback until the inner function is called...
  var ajaxRequest = null;
  var parameterstring  = '';
  // bind our callback then hit the server...
  if (window.XMLHttpRequest)
  {
      // moz et al
      ajaxRequest = new XMLHttpRequest();
      if( undefined == parameters && ajaxRequest )
      {
        ajaxRequest.onreadystatechange = ajaxBindCallback;
        ajaxRequest.open("GET", url, true);
        ajaxRequest.send(null);
        return;
      }
  }
  else
  {
      if (window.ActiveXObject)
      {
        // ie
        try{ ajaxRequest = new ActiveXObject("MSXML2.XMLHTTP");}
        catch (othermicrosoft){ try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (failed) {} }

        if( undefined == parameters && ajaxRequest )
        {
          ajaxRequest.onreadystatechange = ajaxBindCallback;
          ajaxRequest.open("GET", url, true);
          ajaxRequest.send(null);
          return;
        }
      }
  }

  if( ajaxRequest )
  {
    ajaxRequest.onreadystatechange = ajaxBindCallback;
    ajaxRequest.open("POST", url, true);

    // create the parameter string
    // iterate the parameters array
    var parameterString='';
    var n = parameters.length;
    for (var i = 0; i < n; i+=2)
    {
      parameterString += (i > 0 ? "&" : "") + parameters[i] + "=" + encodeURI(parameters[i+1]);
    }

    // set the necessary request headers
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // send requestattr
    ajaxRequest.send(parameterString);

  }
}

function additem(product,variant,variant_holder,action)
{
var qty = parseInt($('#'+variant_holder).attr("available"),10);
if(qty > 0)
{
  var selected = parseInt($('#sel').text(),10)+1;
  var required = parseInt($('#req').text(),10);
  qty--;

  if(!qty){$('#p'+variant_holder).css('color','#CCC');}
  $('#m'+variant_holder).css('color','#000');
  $('#'+variant_holder).attr("available",qty);
  $('#'+variant_holder).val(parseInt($('#'+variant_holder).val(),10)+1);
  $('#sel').text(selected);
  
  if( (!isNaN(selected)) && selected < required )
  {
	$(window).bind('beforeunload', function(){
		return '========= Before You Go ========= \n You have not selected a complete wholesale pack yet\n('
		       +required+' or more items, you have selected '+selected
			   +').\n\nIf you leave this page the items you selected will not be placed in your shopping cart.';
	});
  }
  else
  {
	$(window).unbind('beforeunload');
  }

  var url = '/index.php/Add/?p='+product+'&v='+variant;
	ajaxSend(url,action);
}
}

function subitem(product,variant,variant_holder,action)
{
var avail = parseInt($('#'+variant_holder).attr("available"),10);
var val = $('#'+variant_holder).val();
if(val > 0)
{
  var selected = parseInt($('#sel').text(),10)-1;
  var required = parseInt($('#req').text(),10);
  val--;

  if(!val){$('#m'+variant_holder).css('color','#CCC');}
  $('#p'+variant_holder).css('color','#000');
  $('#'+variant_holder).attr("available",avail+1);
  $('#'+variant_holder).val(val);
  $('#sel').text(selected);
  
  if( isNaN(selected) || selected == 0 || selected >= required )
  {
	$(window).unbind('beforeunload');
  }
  else
  {
	$(window).bind('beforeunload', function(){
		return '========= Before You Go ========= \n You have not selected a complete wholesale pack yet\n('
		       +required+' or more items, you have selected '+selected
			   +').\n\nIf you leave this page the items you selected will not be placed in your shopping cart.';
	});
  }
  
  var url = '/index.php/Sub/?p='+product+'&v='+variant;
  ajaxSend(url,action);
}
}


function submit_nsearch()
{
window.location = '/Find/'+$('#srch').val();
}

function save_order()
{
var e = $('#ohe').val();
if( is_valid_email(e) )
{
	var url = '/OrderSave/'+e;
	ajaxSend(url,function(){alert("Order saved, you can now access this order from any computer by entering your email address and clicking 'View Orders'")});
}
else
	alert("Please enter your email address to save your cart contents");
}


function track_order()
{
var e = $('#ohe').val();
var n = $('#ohn').val();
if( is_valid_email(e) )
	window.location = '/OrderHistory/'+e+'/'+n;
else
	alert("Please enter your email address for order tracking. Only orders that match your email address can be viewed");
}

function change_search_options()
{
return;
age = $('#age_gender').val();
brand = $('#brand').val();
cat = $('#cat').val();
desc = "srdesc|" + $('#srdesc').val();

var q = -1;
var location = window.location.href;

q = location.indexOf('?');
if( -1 != q )
{
  location = location.substr(0,q);
}

q = location.indexOf('catalog');
if( -1 != q )
{
  location = location.substr(0,q+8);
}


window.location = location + '?brand='+brand+'&cat='+cat+'&age_gender='+age;
}

function show_flash(){ Effect.BlindDown('flash'); }

function expand_group(id)
{
	$uparts = document.URL.split('#',2); 
	url = $uparts[0];
	
	if(-1 != url.indexOf('?')){url += '&';}else{url += '?';}
	url += "expand="+id;
	ajaxSend(url,expanded);
}

function loadfooter(){$("#footer").load("/ins/footer.html");}

function SendCountry()
{
	var url = '/Country/' + $('#country').val();
	ajaxSend(url,sidebarshipping);
}

function SendZip()
{
	var url = '/Zip/' + $('#shipzip').val();
	ajaxSend(url,sidebarshipping);
}

function post_it_cancel()
{
  $('#pi').css('display','none');
  $('#cpi').css('display','none');
  var url = '/index.php/Toggle/show_post/0';
  ajaxSend(url,donothing);
}

function post_it()
{
	$('#pi').css('display','none');
	$('#cpi').css('display','none');
	var target = 'Brand/BabyBlooms?pi';
	window.location = target;
}

function loadfooter(){}
function resize_promos()
{
	var maxh = 0;
	  $('.pmobox').each(function(i){
		  if($(this).height()>maxh)
		  {
			  maxh=$(this).height();
		  }
	  });
	  maxh += 'px';
	  $('.pmobox').css('height',maxh);
}
function is_valid_email( email )
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test( email );
}
