function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function Lvl_openWin(u,n,w,h,l,t,c,f) { //v1.0 4LevelWebs
  var ww=((screen.width-w)/2);if(c==1){l=ww;t=(screen.height-h)/2;}if(c==2){l=ww}
	f+=',top='+t+',left='+l;window.open(u,n,f);
}

$(function() {
	if($("a.lbx").length>0){
		$("a.lbx").lightbox({
			fitToScreen: true,
			imageClickClose: true
		});
	}
	
	// set a cookie when an info request is made
	$('.cookieit').click(function(){
		var d = $(this).attr('rel');
		$.cookie("boatname", d);
	});
	
	if ($.cookie("boatname") && $('#frmContact #Boat').length>0){
		$('#frmContact #Boat').val($.cookie("boatname"));
		$(window).unload( function () { $.cookie("boatname", null); } );
	}
	
//  set a cookie when an buy now request is made
  $('.cookieit2').click(function(){
    // get rid of any existing cookies
    $.cookie("saleable_product", null);
    $.cookie("saleable_product_price", null);
    $.cookie("saleable_product_id", null);
    var newDate = new Date;
    //var saleable_product_id = base_encode(newDate.getTime());
    var tstring = newDate.getTime()+'';
    var saleable_product_id = 'ACC' + tstring.substr(3,6);
    var d = $(this).attr('rel').split('|');
    $.cookie("saleable_product", d[0]);
    $.cookie("saleable_product_price", d[1]);
    $.cookie("saleable_product_id", saleable_product_id);
  });
  
  if ($.cookie("saleable_product") && $('#frmContact #saleable_product').length>0){
    $('#frmContact .delivery').hide();
    $('#DeliverHere').change(function(){$('#frmContact .delivery').toggle();});
    var price = $.cookie("saleable_product_price");
    var shipping = shipCost($.cookie("saleable_product_price"));
    var total = parseInt(price) + parseInt(shipping);
    $('#frmContact #saleable_product').val($.cookie("saleable_product"));
    $('#frmContact #saleable_product_price, #frmContact #saleable_product_price2').val('$' + price);
    $('#frmContact #saleable_product_id').val($.cookie("saleable_product_id"));
    $('#frmContact #shipping').val('$' + shipping);
    $('#frmContact #total').val('$' + total);
    
 }
  if ($.cookie("saleable_product") && $('#ppbuynow').length>0){
    // add to paypal as well
    var price = $.cookie("saleable_product_price");
    var shipping = shipCost($.cookie("saleable_product_price"));
    var total = parseInt(price) + parseInt(shipping);
    $('#ppordernumber').val($.cookie("saleable_product") + " (Order Nr: " + $.cookie("saleable_product_id") + ")");
    $('#pptotal').val(total);
  }

  if($('.saleable_image').length>0){
    $('.saleable_image a').lightBox({fixedNavigation:true,imageBtnClose:'/site/images/lightbox-btn-close.gif'});
  }
});

function shipCost(val){
  if(val <= 250) return 25;
  if(val >= 251 && val <= 500) return 30;
  if(val >= 501 && val <= 750) return 35;
  if(val >= 751 && val <= 1000) return 40;
  if(val >= 1001 && val <= 1250) return 45;
  if(val >= 1251 && val <= 1500) return 50;
  if(val >= 1501 && val <= 1750) return 55;
  if(val >= 1751 && val <= 2000) return 60;
  if(val >= 2001 && val <= 2250) return 65;
  if(val >= 2251 && val <= 2500) return 70;
}

function base_encode(num, alphabet) {
  // http://tylersticka.com/
  // Based on the Flickr PHP snippet:
  // http://www.flickr.com/groups/api/discuss/72157616713786392/
  alphabet = alphabet || '0123456789';
  var base_count = alphabet.length;
  var encoded = '';
  while (num >= base_count) {
    var div = num/base_count;
    var mod = (num-(base_count*intval(div)));
    encoded = alphabet.charAt(mod) + encoded;
    num = intval(div);
  }
  if (num) encoded = alphabet.charAt(num) + encoded;
  return encoded;
}

function intval (mixed_var, base) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: stensi
  // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   input by: Matteo
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // *     example 1: intval('Kevin van Zonneveld');
  // *     returns 1: 0
  // *     example 2: intval(4.2);
  // *     returns 2: 4
  // *     example 3: intval(42, 8);
  // *     returns 3: 42
  // *     example 4: intval('09');
  // *     returns 4: 9
  // *     example 5: intval('1e', 16);
  // *     returns 5: 30

  var tmp;

  var type = typeof( mixed_var );

  if (type === 'boolean') {
      return (mixed_var) ? 1 : 0;
  } else if (type === 'string') {
      tmp = parseInt(mixed_var, base || 10);
      return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
  } else if (type === 'number' && isFinite(mixed_var) ) {
      return Math.floor(mixed_var);
  } else {
      return 0;
  }
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
