// This is the wp-e-commerce front end javascript "library"
var base_url = "http://www.westerndairyassociation.org/wp";
var WPSC_URL = "http://www.westerndairyassociation.org/wp/wp-content/plugins/wp-e-commerce";
var WPSC_IMAGE_URL = "http://www.westerndairyassociation.org/wp/wp-content/uploads/wpsc/product_images/";
var WPSC_DIR_NAME = "wp-e-commerce";

/* LightBox Configuration start*/
var fileLoadingImage = "http://www.westerndairyassociation.org/wp/wp-content/plugins/wp-e-commerce/images/loading.gif";
var fileBottomNavCloseImage = "http://www.westerndairyassociation.org/wp/wp-content/plugins/wp-e-commerce/images/closelabel.gif";
var fileThickboxLoadingImage = "http://www.westerndairyassociation.org/wp/wp-content/plugins/wp-e-commerce/images/loadingAnimation.gif";
var resizeSpeed = 9;  // controls the speed of the image resizing (1=slowest and 10=fastest)
var borderSize = 10;  //if you adjust the padding in the CSS, you will need to update this variable

// this function is for binding actions to events and rebinding them after they are replaced by AJAX
// these functions are bound to events on elements when the page is fully loaded.
// empty the cart using ajax when the form is submitted,  
function check_make_purchase_button(){
	toggle = jQuery('#noca_gateway').attr('checked');
	if(toggle == true){
		//jQuery('.make_purchase').hide();
		jQuery('#OCPsubmit').show();
	}else{
		jQuery('.make_purchase').show();	
		jQuery('#OCPsubmit').hide();		
	}
}	

function saveFormData(formID) {
	// Save form data in JSON string
	var cookieName = "wda-"+formID;
	//var data = jQuery.toJSON(jQuery('#'+formID+' form').serializeObject());
	var data = jQuery('#'+formID+' form').serialize();
	jQuery.cookie(cookieName, data, {expires: 365});
	jQuery('#formSaved').fadeIn().delay(3000).fadeOut();
}

function loadFormData(formID) {
	var cookieName, data, entry;
	cookieName = "wda-"+formID;
	data = decodeURIComponent(jQuery.cookie(cookieName)).split('&');	
	
	jQuery.each(data, function(i, item){
		entry = item.split('=');	
		if ( entry[1] != '' )
			// Set inputs
			// Set Textareas
			// Set Checkboxes
			// switch on input type if possible, otherwise, set all 4 per value.
			switch ( entry[1] ) {
				// Checkboxes
				case 'No':
				case 'Yes':
					jQuery("input[name='"+entry[0]+"']").each(function() {
						if( jQuery(this).val() == entry[1] ) {
							jQuery(this).attr("checked","checked");
						}
					});
					break;
				default:
					var myvalue = decodeURIComponent(entry[1]).split('+').join(' ');
					// Radio buttons
					if ( jQuery("[value='"+myvalue+"']").length ) {
						jQuery("[value='"+myvalue+"']").attr('checked','checked');
					} else {					
						jQuery("[name='"+entry[0]+"']").val(myvalue);
					}
					break;
			}
	});
	jQuery('#formLoaded').fadeIn().delay(1500).fadeOut();
	
}
jQuery.fn.serializeObject = function()
{
	var o = {};
	var a = this.serializeArray();
	jQuery.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

// make sure the $ is pointing to JQuery and not some other library
(function($){
    $.fn.loadFormButtons = function() {
		var html, save, load, notices, formID, name;
        //load the form buttons for the called form
 		formID = $(this).parent('div').attr('id');
		name = 'wda-'+formID;
		save = "<div id='formSave'><a href='#' rel='"+formID+"'>Save Data</a></div>";
		load = "<div id='formLoad'><a href='#' rel='"+formID+"'>Load Data</a></div>";
		notices = "<div id='formNotice'><div id='formSaved'>Saved...<p>Form data is saved using cookies, if you delete your cookies, your data will be lost.</p></div><div id='formLoaded'>Loaded</div></div>";
		// Show load button if data exists
		if ( jQuery.cookie(name) != '' ) {
			html = save + load;
		} else {
			html = save;
		}
		$(this).parent('div').prepend('<div id="formActionButtons">'+html+notices+'</div>');
    }
})(jQuery);

jQuery(document).ready(function () {
  	
  	// Tabify FUTP page
  	//jQuery('ul#futp').tabify();
  	
  	// FUTP You Tube Playlist
  	/*
  	jQuery('ul.ytplaylist').ytplaylist({
  		addThumbs: true, 
  		autoPlay: false, 
  		holderId: 'ytvideo2'
  	});
  	*/
  	// Define basic Shadowbox options for using the image player.
    var options = {
		handleOversize: 'none',
		animate: true,
		displayNav: true,
		handleUnsupported: 'remove',
		initialHeight: 385,
		initialWidth: 480
    };
    Shadowbox.init(options);
    jQuery('ul.ytplaylist li a').each(function(){
    	var video = jQuery(this).attr('href');
    	video = video.split('/');
		jQuery(this).prepend('<img src="'+jQuery.jYoutube( video.pop(), 'small')+'" height="45" width="60" />');    	
    });
  	// Load form buttons if there is a savable form on the page
	if ( jQuery('div.saveform form').length == 1 ) {
		//loadFormButtons();
		jQuery('div.saveform').loadFormButtons();
		jQuery('#formSave a').live('click', function(){
			saveFormData(jQuery(this).attr('rel'));
			return false;
		});
		jQuery('#formLoad a').live('click', function(){
			loadFormData(jQuery(this).attr('rel'));
			return false;
		});
		var offset = jQuery('#formActionButtons').offset();
		jQuery(window).scroll(function() {
			var scroll = parseInt(jQuery(this).scrollTop());
			if ( offset.top < scroll ) {
				jQuery('#formActionButtons').css('top', scroll + "px");
			} else {
				jQuery('#formActionButtons').css('top', offset.top + "px");			
			}
		});
	}
	
	if ( jQuery('#widgetshoppingcart').length == 1 ) {
		
		var offset = jQuery('#widgetshoppingcart').offset();
		var itemh = jQuery('#widgetshoppingcart').height();
		var winh = jQuery('body').height();
		
		jQuery(window).scroll(function() {
			var scroll = parseInt(jQuery(this).scrollTop());
			if ( offset.top < scroll ) {
				var diff = parseInt(scroll-offset.top+20)
				if ( (diff + itemh + 870) < winh ) {
					//jQuery('#widgetshoppingcart').stop().animate({"marginTop": (diff) + "px"}, "fast" );
					jQuery('#widgetshoppingcart').css({'position':'fixed','top':'5px'});
				}
			} else {
				jQuery('#widgetshoppingcart').css({'position':'relative'});
			}
		});	
	}
  	
	//Open outside links in a new window -- boo!
	jQuery("a[href^='http']").not("[href*='westerndairyassociation.org']").attr('target','_blank');
	
	//Update tax status on Tax ID input for shopping cart
	jQuery("input#wpsc_checkout_form_18").keyup(function(){
		if ( jQuery(this).val() != '' ) {
			// Verify Tax Free is not selected yet
			if ( jQuery("#wpsc_checkout_form_6").val() != 'UT' ) {
				// Select Tax-Free for user
				jQuery("option[value='UT']").attr('selected', true);
				// Force script update
				set_billing_country("region_country_form_6", "6");
	
			}			
		} 
	});
	
  	//this bit of code runs on the checkout page. 
  	// If the checkbox is selected it copies the valus in the billing country and puts it in the shipping country form fields.
	//jQuery('.wpsc_shipping_forms').hide();
	jQuery("#shippingSameBilling").click(function(){
		jQuery('.wpsc_shipping_forms').toggle();
		// If checked
		//jQuery("#shippingSameBilling").livequery(function(){
		
			if(jQuery(this).is(":checked")){
				var fname = jQuery("input[name='collected_data[2]']").val();
				var lname = jQuery("input[name='collected_data[3]']").val();            
				var school = jQuery("input[name='collected_data[19]']").val();            
				var addr = jQuery("textarea[name='collected_data[4]']").val();
				var city = jQuery("input[name='collected_data[5]']").val(); 
				var pcode = jQuery("input[name='collected_data[7]']").val();
				var phone = jQuery("input[name='collected_data[17]']").val(); 
				var email = jQuery("input[name='collected_data[8]']").val();
				var state = jQuery("select[name='collected_data[6][1]'] :selected").text();
				var country = jQuery("select[name='collected_data[6][0]'] :selected").text();       
				
				jQuery("input[name='collected_data[10]']").val(fname);
				jQuery("input[name='collected_data[11]']").val(lname); 
				jQuery("input[name='collected_data[21]']").val(school); 
				jQuery("textarea[name='collected_data[12]']").val(addr);
				jQuery("input[name='collected_data[13]']").val(city);
				jQuery("input[name='collected_data[14]']").val(state);				
				jQuery("input[name='collected_data[16]']").val(pcode);		
				
			} else {
			
			}
			//otherwise, hide it
			//jQuery("#extra").hide("fast");
		//});
	});
	// Submit the product form using AJAX
	jQuery("form.product_form").submit(function() {
	// we cannot submit a file through AJAX, so this needs to return true to submit the 
	// form normally if a file formfield is present
	    file_upload_elements = jQuery.makeArray(jQuery('input[type=file]', jQuery(this)));
		if(file_upload_elements.length > 0) {
			return true;
		} else {
			form_values = jQuery(this).serialize();
			// Sometimes jQuery returns an object instead of null, using length tells 
			// us how many elements are in the object, which is more reliable than comparing the object to null
			if(jQuery('#fancy_notification').length == 0) {
				jQuery('div.wpsc_loading_animation',this).css('visibility', 'visible');
			}
			jQuery.post( 'index.php?ajax=true', form_values, function(returned_data) {
				eval(returned_data);
				jQuery('div.wpsc_loading_animation').css('visibility', 'hidden');
				
				if(jQuery('#fancy_notification') != null) {
					jQuery('#loading_animation').css("display", 'none');
					//jQuery('#fancy_notificationimage').css("display", 'none');
				}
				
			});
			wpsc_fancy_notification(this);
			return false;
		}
	});
  
  
	//  this is for storing data with the product image, like the product ID, for things like dropshop and the the ike.
	jQuery("form.product_form").livequery(function(){
			product_id = jQuery('input[name=product_id]',this).val();
			image_element_id = 'product_image_'+product_id;
			jQuery("#"+image_element_id).data("product_id", product_id);			
			parent_container = jQuery(this).parents('div.product_view_'+product_id);
			jQuery("div.item_no_image", parent_container).data("product_id", product_id);
	});
	//jQuery("form.product_form").trigger('load');
	
	// Toggle the additional description content  
	jQuery("a.additional_description_link").click(function() {
		parent_element = jQuery(this).parent('.additional_description_span');
		jQuery('.additional_description',parent_element).toggle();
		return false;
	});
	
	
	// update the price when the variations are altered.
	jQuery("div.wpsc_variation_forms .wpsc_select_variation").change(function() {
		parent_form = jQuery(this).parents("form.product_form");
		form_values =jQuery("input[name=product_id],div.wpsc_variation_forms .wpsc_select_variation",parent_form).serialize( );
		jQuery.post( 'index.php?update_product_price=true', form_values, function(returned_data) {
			eval(returned_data);
			if(product_id != null) {
				target_id = "product_price_"+product_id;
				buynow_id = "BB_BuyButtonForm"+product_id;
				//document.getElementById(target_id).firstChild.innerHTML = price;			
				if(jQuery("input#"+target_id).attr('type') == 'text') {
					jQuery("input#"+target_id).val(numeric_price);
				} else {
					jQuery("#"+target_id+".pricedisplay").html(price);
				}
			}
		});
		return false;
	});




	jQuery("form.wpsc_empty_the_cart").livequery(function(){
		jQuery(this).submit(function() {
			form_values = "ajax=true&";
			form_values += jQuery(this).serialize();
			jQuery.post( 'index.php', form_values, function(returned_data) {
				eval(returned_data);
			});
			return false;
		});
	});

	jQuery("form.wpsc_empty_the_cart span.emptycart a").livequery(function(){
		jQuery(this).click(function() {
			parent_form = jQuery(this).parents("form.wpsc_empty_the_cart");
			form_values = "ajax=true&";
			form_values += jQuery(parent_form).serialize();
			jQuery.post( 'index.php', form_values, function(returned_data) {
				eval(returned_data);
			});
			return false;
		});
	}); 
});

// update the totals when shipping methods are changed.
function switchmethod(key,key1){
// 	total=document.getElementById("shopping_cart_total_price").value;
	form_values = "ajax=true&";
	form_values += "wpsc_ajax_action=update_shipping_price&";
	form_values += "key1="+key1+"&";
	form_values += "key="+key;
	jQuery.post( 'index.php', form_values, function(returned_data) {
		eval(returned_data);
	});
}

// submit the country forms.
function submit_change_country(){
	document.forms.change_country.submit();
}

// submit the fancy notifications forms.
function wpsc_fancy_notification(parent_form){
	if(typeof(WPSC_SHOW_FANCY_NOTIFICATION) == 'undefined'){
	    WPSC_SHOW_FANCY_NOTIFICATION = true;
	}
	if((WPSC_SHOW_FANCY_NOTIFICATION == true) && (jQuery('#fancy_notification') != null)){
	    var options = {
			margin: 1 ,
			border: 1 ,
			padding: 1 ,
			scroll: 1 
		};
	
	    form_button_id = jQuery(parent_form).attr('id') + "_submit_button";
	    //return;
	    var container_offset = {};
	    new_container_offset = jQuery('#products_page_container').offset(options, container_offset);
	    
		if(container_offset['left'] == null) {
			container_offset['left'] = new_container_offset.left;
			container_offset['top'] = new_container_offset.top;
	    }    
	
	    var button_offset = {};
	    new_button_offset = jQuery('#'+form_button_id).offset(options, button_offset)
	    
	    if(button_offset['left'] == null) {
			button_offset['left'] = new_button_offset.left;
			button_offset['top'] = new_button_offset.top;
	    }
	        
	    jQuery('#fancy_notification').css("left", (button_offset['left'] - container_offset['left'] + 10) + 'px');
	    jQuery('#fancy_notification').css("top", ((button_offset['top']  - container_offset['top']) -60) + 'px');   
	    jQuery('#fancy_notification').css("display", 'block');
	    jQuery('#loading_animation').css("display", 'block');
	    jQuery('#fancy_notification_content').css("display", 'none');  
	}
}

function shopping_cart_collapser() {
  switch(jQuery("#sliding_cart").css("display")) {
    case 'none':
    jQuery("#sliding_cart").slideToggle("fast",function(){
			jQuery.post( 'index.php', "ajax=true&set_slider=true&state=1", function(returned_data) { });
      jQuery("#fancy_collapser").attr("src", (WPSC_URL+"/images/minus.png"));
		});
    break;
    
    default:
    jQuery("#sliding_cart").slideToggle("fast",function(){
			jQuery.post( 'index.php', "ajax=true&set_slider=true&state=0", function(returned_data) { });
      jQuery("#fancy_collapser").attr("src", (WPSC_URL+"/images/plus.png"));
		});
    break;
	}
  return false;
}
  
function set_billing_country(html_form_id, form_id){
	var billing_region = '';
	country = jQuery(("div#"+html_form_id+" select[class=current_country]")).val();
	region = jQuery(("div#"+html_form_id+" select[class=current_region]")).val();
	if(/[\d]{1,}/.test(region)) {
		billing_region = "&billing_region="+region;
	}
	
	form_values = "wpsc_ajax_action=change_tax&form_id="+form_id+"&billing_country="+country+billing_region;
	jQuery.post( 'index.php', form_values, function(returned_data) {
		eval(returned_data);
	});
	//ajax.post("index.php",changetaxntotal,("ajax=true&form_id="+form_id+"&billing_country="+country+billing_region));
}


// Copyright (c) 2005 Timothy R. Morgan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// mini/ajax.js - http://timmorgan.org/mini
// var fvd = 0;
function ajax_item(e){if(typeof e=='string')e=document.getElementById(e);return e};
function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};

ajax={};
ajax.x=function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}};
ajax.serialize=function(f)
  {
  var g=function(n)
    {
    return f.getElementsByTagName(n)
    };
  var nv=function(e)
    {
    if(e.name)
      {
      return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);
      } else {return '';}
    };
  var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');
  };
  
ajax.send=function(u,f,m,a){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText)};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a)};
ajax.get=function(url,func){ajax.send(url,func,'GET')};
ajax.gets=function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText};
ajax.post=function(url,func,args){ajax.send(url,func,'POST',args)};
ajax.update=function(url,elm){var e=ajax_item(elm);var f=function(r){e.innerHTML=r};ajax.get(url,f)};
ajax.submit=function(url,elm,frm){var e=ajax_item(elm);var f=function(r){e.innerHTML=r};ajax.post(url,f,ajax.serialize(frm))};

/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {
	
$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});
		
		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
		
		// Make sure it is running
		q.stopped = false;
		
		// Run it immediately for the first time
		q.run();
		
		// Contnue the chain
		return this;
	},
	
	expire: function(type, fn, fn2) {
		var self = this;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context && 
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});
		
		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context || document;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;
	
	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;
	
	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
	
	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;
		
		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});
			
		// Clear out matched elements
		this.elements = [];
		
		// Stop the Live Query from running until restarted
		this.stopped = true;
	},
	
	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;
		
		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);
		
		// Set elements to the latest set of matched elements
		this.elements = els;
		
		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);
			
			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});
			
			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,
	
	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},
	
	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},
	
	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},
	
	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;
			
			// Save a reference to the original method
			var old = $.fn[n];
			
			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);
				
				// Request a run of the Live Queries
				$.livequery.run();
				
				// Return the original methods result
				return r;
			}
		});
	},
	
	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});
		
		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},
	
	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
	// Call the original init and save the result
	var r = init.apply(this, arguments);
	
	// Copy over properties if they exist already
	if (a && a.selector)
		r.context = a.context, r.selector = a.selector;
		
	// Set properties
	if ( typeof a == 'string' )
		r.context = c || document, r.selector = a;
	
	// Return the result
	return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;
	
})(jQuery);

var testsuccess = 0;
var lnid = new Array();


function categorylist(url) {
  self.location = url;
}

var noresults=function(results) {
  return true;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


var getresults=function(results) {
  eval(results);
  if(window.drag_and_drop_cart_updater) {
     drag_and_drop_cart_updater();
	}
  if(document.getElementById('loadingimage') != null) {
    document.getElementById('loadingindicator').style.visibility = 'hidden';
	} else if(document.getElementById('alt_loadingimage') != null) {
    document.getElementById('alt_loadingindicator').style.visibility = 'hidden';
	}
  if((document.getElementById('sliding_cart') != null) && (document.getElementById('sliding_cart').style.display == 'none')) {
    jQuery("#fancy_collapser").attr("src", (WPSC_URL+"/images/minus.png"));
    jQuery("#sliding_cart").show("fast",function(){
    ajax.post("index.php",noresults,"ajax=true&set_slider=true&state=1"); });
	}
  if(document.getElementById('fancy_notification') != null) {
    jQuery('#loading_animation').css("display", 'none');
    //jQuery('#fancy_notificationimage').css("display", 'none');
	}
}
/*  
function set_billing_country(html_form_id, form_id){
  var billing_region = '';
  country = jQuery(("div#"+html_form_id+" select[@class=current_country]")).val();
  region = jQuery(("div#"+html_form_id+" select[@class=current_region]")).val();
  if(/[\d]{1,6}/.test(region)) { // number over 6 digits for a region ID? yeah right, not in the lifetime of this code
    billing_region = "&billing_region="+region;
	}
  ajax.post("index.php",getresults,("ajax=true&changetax=true&form_id="+form_id+"&billing_country="+country+billing_region));
  //ajax.post("index.php",changetaxntotal,("ajax=true&form_id="+form_id+"&billing_country="+country+billing_region));
}*/

function submitform(frm, show_notification)
  {
  if(show_notification != false)
    {
    show_notification = true;
    }
  //alert(ajax.serialize(frm));
  ajax.post("index.php?ajax=true&user=true",getresults,ajax.serialize(frm));
  if(document.getElementById('loadingimage') != null)
    {
    document.getElementById('loadingimage').src = WPSC_URL+'/images/indicator.gif';
    document.getElementById('loadingindicator').style.visibility = 'visible';
    } 
    else if(document.getElementById('alt_loadingimage') != null)
    {
    document.getElementById('alt_loadingimage').src = WPSC_URL+'/images/indicator.gif';
    document.getElementById('alt_loadingindicator').style.visibility = 'visible';
    }     
  if((show_notification == true) && (document.getElementById('fancy_notification') != null))
    {
    var options = {
      margin: 1 ,
      border: 1 ,
      padding: 1 ,
      scroll: 1 
      };

    form_button_id = frm.id + "_submit_button";
    //alert(form_button_id);

    var container_offset = {};
    new_container_offset = jQuery('#products_page_container').offset(options, container_offset);
    
		if(container_offset['left'] == null) {
      container_offset['left'] = new_container_offset.left;
      container_offset['top'] = new_container_offset.top;
    }
    

    var button_offset = {};
    new_button_offset = jQuery('#'+form_button_id).offset(options, button_offset)

    
    if(button_offset['left'] == null) {
      button_offset['left'] = new_button_offset.left;
      button_offset['top'] = new_button_offset.top;
    }
    
    
    jQuery('#fancy_notification').css("left", (button_offset['left'] - container_offset['left'] + 10) + 'px');
    jQuery('#fancy_notification').css("top", ((button_offset['top']  - container_offset['top']) -60) + 'px');
    
    
    
    jQuery('#fancy_notification').css("display", 'block');
    jQuery('#loading_animation').css("display", 'block');
    jQuery('#fancy_notification_content').css("display", 'none');  
    }
  return false;
  }


function prodgroupswitch(state)
  {
  if(state == 'brands')
    {
    jQuery('.categorydisplay').css("display", 'none');
    jQuery('.branddisplay').css("display", 'block');
    }
    else if(state == 'categories')
      {
      jQuery('.categorydisplay').css("display", 'block');
      jQuery('.branddisplay').css("display", 'none');
      }
  return false;
  }
  
var previous_rating;
function ie_rating_rollover(id,state)
  {
  target_element = document.getElementById(id);
  switch(state)
    {
    case 1:
    previous_rating = target_element.style.background;
    target_element.style.background = "url("+WPSC_URL+"/images/blue-star.gif)";
    break;
    
    default:
    if(target_element.style.background != "url("+WPSC_URL+"/images/gold-star.gif)")
      {
      target_element.style.background = previous_rating;
      }
    break;
    }
  }  
  
var apply_rating=function(results)
  {
  outarr = results.split(",");
  //alert(results);
  for(i=1;i<=outarr[1];i++)
    {
    id = "star"+outarr[0]+"and"+i+"_link";
    document.getElementById(id).style.background = "url("+WPSC_URL+"/images/gold-star.gif)";
    }
    
  for(i=5;i>outarr[1];i--)
    {
    id = "star"+outarr[0]+"and"+i+"_link";
    document.getElementById(id).style.background = "#c4c4b8";
    }
  lnid[outarr[0]] = 1; 
    
  rating_id = 'rating_'+outarr[0]+'_text';
  //alert(rating_id);
  if(document.getElementById(rating_id).innerHTML != "Your Rating:")
    {
    document.getElementById(rating_id).innerHTML = "Your Rating:";
    }
    
  saved_id = 'saved_'+outarr[0]+'_text';
  document.getElementById(saved_id).style.display = "inline";
  update_vote_count(outarr[0]);
  }
  
function hide_save_indicator(id)
  {
  document.getElementById(id).style.display = "none";
  }
  
function rate_item(prodid,rating)
  {
  ajax.post("index.php",apply_rating,"ajax=true&rate_item=true&product_id="+prodid+"&rating="+rating);
  }
  
function update_vote_count(prodid)
  {
  var update_vote_count=function(results)
    {
    outarr = results.split(",");
    vote_count = outarr[0];
    prodid = outarr[1];
    vote_count_id = 'vote_total_'+prodid;
    document.getElementById(vote_count_id).innerHTML = vote_count;
    }
  ajax.post("index.php",update_vote_count,"ajax=true&get_rating_count=true&product_id="+prodid);
  }

  
function update_preview_url(prodid)
  {
  image_height = document.getElementById("image_height").value;
  image_width = document.getElementById("image_width").value;
  if(((image_height > 0) && (image_height <= 1024)) && ((image_width > 0) && (image_width <= 1024)))
    {
    new_url = "index.php?productid="+prodid+"&height="+image_height+"&width="+image_width+"";
    document.getElementById("preview_link").setAttribute('href',new_url);
    }
    else
      {
      new_url = "index.php?productid="+prodid+"";
      document.getElementById("preview_link").setAttribute('href',new_url);
      }
  return false;
  }
  
function change_variation(product_id, variation_ids, special) {
  value_ids = '';
  special_prefix = "";
  if(special == true) {
    form_id = "specials_"+product_id;
	} else {
    form_id = "product_"+product_id;
	}
  for(var i in variation_ids) {
    if(!isNaN(parseInt(i))) {
      variation_name = "variation["+variation_ids[i]+"]";
      value_ids += "&variation[]="+document.getElementById(form_id).elements[variation_name].value;
		}
	}
  if(special == true) {
    var return_price=function(results) { 
      eval(results);
      if(product_id != null) {
        target_id = "special_product_price_"+product_id;
				buynow_id = "BB_BuyButtonForm"+product_id;
				document.getElementById(target_id).firstChild.innerHTML = price;
				if (price.substring(27,price.indexOf("&"))!='')
					document.getElementById(buynow_id).item_price_1.value = price.substring(27,price.indexOf("&"));
				}
      }
	} else {
    var return_price=function(results) {
      //alert(results);
      eval(results);
      if(product_id != null) {
        target_id = "product_price_"+product_id;
				buynow_id = "BB_BuyButtonForm"+product_id;
				//document.getElementById(target_id).firstChild.innerHTML = price;			
				if(jQuery("input#"+target_id).attr('type') == 'text') {
				  jQuery("input#"+target_id).val(numeric_price);
				} else {
				  jQuery("#"+target_id+" span.pricedisplay").html(price);
				}
			}
		}
	}
  ajax.post("index.php",return_price,"ajax=true&get_updated_price=true&product_id="+product_id+value_ids);
}
function show_details_box(id,image_id) {
  state = document.getElementById(id).style.display; 
  if(state != 'block') {
    document.getElementById(id).style.display = 'block';
    document.getElementById(image_id).src = WPSC_URL+"/images/icon_window_collapse.gif";
	} else {
		document.getElementById(id).style.display = 'none';
		document.getElementById(image_id).src = WPSC_URL+"/images/icon_window_expand.gif";
	}
  return false;
}
  
var register_results=function(results) {
  jQuery("div#TB_ajaxContent").html(results);
  jQuery('div#checkout_login_box').css("border", '1px solid #339933');
  jQuery('div#checkout_login_box').css("background-color", '#e8fcea');
}
  
function submit_register_form(frm)
  {
  jQuery('img#register_loading_img').css("display", 'inline');
  ajax.post("index.php?ajax=true&action=register",register_results,ajax.serialize(frm));

  return false;
  }

var fadeInSuggestion = function(suggestionBox, suggestionIframe) {
	$(suggestionBox).fadeTo(300,1);
};

var fadeOutSuggestion = function(suggestionBox, suggestionIframe) {
	$(suggestionBox).fadeTo(300,0);
};

function change_pics(command){
	location1 = window.location.href;

	if (command == 1){
		document.getElementById('out_view_type').innerHTML = "<input type='hidden' id='view_type' name='view_type' value='default'>";
		document.getElementById('out_default_pic').innerHTML ="<img id='default_pic' src='"+WPSC_URL+"/images/default-on.gif'>";
		document.getElementById('out_grid_pic').innerHTML ="<img id='grid_pic' style='cursor:pointer;' onclick='change_pics(0)' src='"+WPSC_URL+"/images/grid-off.gif'>";
		if (location1.search(/view_type/)!=-1) {
			$new_location = location1.replace("grid","default");
		} else {
		  if (location1.search(/\?/)!=-1) {
				$new_location = location1+"&view_type=default";
			} else {
				$new_location = location1+"?view_type=default";
			}
		}
		window.location = $new_location;
	} else {
		document.getElementById('out_view_type').innerHTML = "<input type='hidden' id='view_type' name='view_type' value='grid'>";
		document.getElementById('out_default_pic').innerHTML ="<img id='default_pic'  style='cursor:pointer;' onclick='change_pics(1)' src='"+WPSC_URL+"/images/default-off.gif'>";
		document.getElementById('out_grid_pic').innerHTML ="<img id='grid_pic' src='"+WPSC_URL+"/images/grid-on.gif'>";
		if (location1.search(/view_type/)!=-1) {
			$new_location = location1.replace("default","grid");
		} else {
		  if (location1.search(/\?/)!=-1) {
				$new_location = location1+"&view_type=grid";
			} else {
				$new_location = location1+"?view_type=grid";
			}
		}
		
		window.location = $new_location;
	}
}

function log_buynow(form){
	id = form.product_id.value;
	price = form.item_price_1.value;
	ajax.post("index.php",noresults,"ajax=true&buynow=true&product_id="+id+"price="+price);
}

function gotoexternallink(link){
	window.location = link;
}

function manage_extras(product_id, extras_id, special) {
	value_ids = '';
	special_prefix = "";
	extra_idss='';
	document.getElementById('extras_indicator'+product_id+extras_id).style.display='block';
	if(special == true) {
		form_id = "specials_"+product_id;
	} else {
		form_id = "product_"+product_id;
	}
	
	jQuery(document).ready(function(){
		extra_ids=jQuery("input.extras_"+product_id+":checked");
	});
	
	jQuery.each(extra_ids, function(key, value) {
		extra_idss += "&extra[]="+extra_ids[key].value;
	});
	pm='stay';

	if(special == true) {
		var return_price=function(results) {
			//alert(results);
			eval(results);
			if(product_id != null) {
				target_id = "special_product_price_"+product_id;
				buynow_id = "BB_BuyButtonForm"+product_id;
				document.getElementById(target_id).firstChild.innerHTML = price;
				if (price.substring(27,price.indexOf("&"))!='')
					document.getElementById(buynow_id).item_price_1.value = price.substring(27,price.indexOf("&"));
			}
			document.getElementById('extras_indicator'+product_id+extras_id).style.display='none';
		}
	} else {
		var return_price=function(results) {
			eval(results);
			if(product_id != null) {
				target_id = "product_price_"+product_id;
				buynow_id = "BB_BuyButtonForm"+product_id;
				document.getElementById(target_id).firstChild.innerHTML = price;
				if (price.substring(27,price.indexOf("&"))!='')
					document.getElementById(form_id).item_price_1.value = price.substring(27,price.indexOf("&"));
			}
			document.getElementById('extras_indicator'+product_id+extras_id).style.display='none';
		}
	}
ajax.post("index.php",return_price,"ajax=true&get_updated_price=true&pm="+pm+"&product_id="+product_id+extra_idss);
}

function store_list(){
	address = document.getElementById('user_address').value;
	city = document.getElementById('user_city').value;
	if ((address != '')&&(city != '')) {
		document.getElementById('gloc_loading').style.display='block';
		ajax.post("index.php",return_store_list,"ajax=true&store_list=true&addr="+address+"&city="+city);
	}
}

var return_store_list=function(results) {
	document.getElementById('gloc_storelist').innerHTML=results;
	document.getElementById('gloc_loading').style.display='none';
	return true;
}

function autocomplete(event) {
	if(!event){
		event=window.event;
	}
	if(event.keyCode){
		keyPressed=event.keyCode;
	}else if(event.which){
		keyPressed=event.which;
	}
	str = document.getElementById('wpsc_search_autocomplete').value;
	if (str != '') {
		ajax.post("index.php",autocomplete_results,"wpsc_live_search=true&keyword="+str);
	} else {
		jQuery('#blind_down').slideUp(100);
	}
}

var autocomplete_results=function(results) {
	document.getElementById('blind_down').innerHTML=results;
	if (document.getElementById('blind_down').style.display!='block') {
		jQuery('#blind_down').slideDown(200);
	}
	return true;
}

function statusTextKeyPress(event){
	if(!event){
		event=window.event;
	}
	if(event.keyCode){
		keyPressed=event.keyCode;
	}else if(event.which){
		keyPressed=event.which;
	}
	if(keyPressed==9){
		return false;
	}
	if(keyPressed==13){
		newstatus = document.getElementById('status_change_text').value;
		ajax.post("index.php",submit_user_status,"ajax=true&submitstatus=true&status="+newstatus);
		return false;
	}
	if(keyPressed==27){
		document.getElementById('edit_status_select').style.display='none';
		return false;
	}
	return true;
}
// function switchmethod(key,key1){
// // 	total=document.getElementById("shopping_cart_total_price").value;
// 	ajax.post("index.php",usps_method_switch,"ajax=true&uspsswitch=true&key1="+key1+"&key="+key+"&total="+total);
// }

var usps_method_switch=function (results){
	shipping = results.split('---');
	shipping1 = shipping[1];
	jQuery("#checkout_total").html(shipping[0]);
	
	jQuery('.total > .pricedisplay').remove();
	jQuery('.total > .totalhead').after(shipping[0]);
	jQuery('.postage > .pricedisplay').remove();
	jQuery('.postage > .postagehead').after(shipping1);
}

function add_meta_box(results){
	jQuery(".wpsc_buy_button").before(results);
	jQuery('.time_requested').datepicker({ dateFormat: 'yy-mm-dd' });
}

function submit_purchase(){
	document.forms.ideal_form.submit();
}

function do_nothing() {
	return;
}

jQuery(document).ready(
	function() {
		if (jQuery("#openair").val() == 1) {
			var max_height = 0;
			var min_offset = 9999;
			var max_left_offset = 0;
			var top_offset = 0;
			jQuery("div.product_grid_item").each(
				function() {
					jQuery(this).css('margin','0');
					if (jQuery(this).height() > max_height) {
						max_height = jQuery(this).height();
					}
					var offset = jQuery(this).offset();
					if (offset.left <= min_offset) {
						min_offset = offset.left;
					}
					if (offset.top > top_offset) {
						top_offset = offset.top;
					}
					if (offset.left > max_left_offset) {
						max_left_offset = offset.left;
					}
				}
			);
			
			jQuery("div.product_grid_item:last").each(
				function() {
					var offset = jQuery(this).offset();
					
					if (offset.left != max_left_offset) {
						jQuery(this).css('border-right','1px solid #ddd');
					}
				}
			);
			
			jQuery("div.product_grid_item").each(
				function() {
					
					
					
					var offset = jQuery(this).offset();
					if (offset.left == min_offset) {
						setTimeout('do_nothing', 200);
						jQuery(this).css('border-left','0px solid #ddd');
					}
					
					if (offset.top == top_offset) {
						jQuery(this).css('border-bottom','0px solid #ddd');
					}
					jQuery(this).height(max_height+30);
				}
			);
		}
		
		
		
		jQuery("div.custom_gateway table").each(
			function() {
				if(jQuery(this).css('display') == 'none') {
					jQuery('input', this).attr( 'disabled', true);
				}
			}
		);
		
		jQuery("input.custom_gateway").change(
			function() {
				if(jQuery(this).attr('checked') == true) {
					parent_div = jQuery(this).parents("div.custom_gateway");
					jQuery('table input',parent_div).attr( 'disabled', false);
					jQuery('table',parent_div).css('display', 'block');
				  jQuery("div.custom_gateway table").not(jQuery('table',parent_div)).css('display', 'none');
				  
				  jQuery("div.custom_gateway table input").not(jQuery('table input',parent_div)).attr( 'disabled', true);
				}
			}
		);
	}
);

/*
 * Thickbox 2.1 - jQuery plugin for displaying content in a box above the page
 * 
 * Copyright (c) 2006, 2007 Cody Lindley (http://www.codylindley.com)
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
jQuery(document).ready(TB_init);

// add thickbox to href elements that have a class of .thickbox
function TB_init(){
	jQuery("a.thickbox").click(function(event){
		// stop default behaviour
		event.preventDefault();
		// remove click border
		this.blur();
	
		// get caption: either title or name attribute
		var caption = this.title || this.name || "";
		
		// get rel attribute for image groups
		var group = this.rel || false;
		
		// display the box for the elements href
		TB_show(caption, this.href, group);
	});
}

// called when the user clicks on a thickbox link
function TB_show(caption, url, rel) {
	// create iframe, overlay and box if non-existent
	if ( !jQuery("#TB_HideSelect").length ) {
		jQuery("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
		jQuery("#TB_overlay").click(TB_remove);
	}
	// TODO replace or check if event is already assigned
	jQuery(window).scroll(TB_position);
	
	// TODO replace
	TB_overlaySize();
	
	// TODO create loader only once, hide and show on demand
	jQuery("body").append("<div id='TB_load'><img src='"+fileThickboxLoadingImage+"' /></div>");
	TB_load_position();
	
	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// check for images
	if ( baseURL.match(imageURL) ) {
		var dummy = { caption: "", url: "", html: "" };
		
		var prev = dummy,
			next = dummy,
			imageCount = "";
			
		// if an image group is given
		if ( rel ) {
			function getInfo(image, id, label) {
				return {
					caption: image.title,
					url: image.href,
					html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
				}
			}
		
			// find the anchors that point to the group
			var imageGroup = jQuery("a[rel="+rel+"]").get();
			var foundSelf = false;
			var imageTitle = 'Gallery'; //default to something sane
			// loop through the anchors, looking for ourself, saving information about previous and next image
			for (var i = 0; i < imageGroup.length; i++) {
				var image = imageGroup[i];
				var urlTypeTemp = image.href.match(imageURL);
				
				// look for ourself
				if ( image.href == url ) {
					foundSelf = true;
					imageCount = "Image " + (i + 1) + " of "+ (imageGroup.length);
          if(image.rel != null) {
            imageTitle = image.rel.replace(/_/, " ");
					}
				} else {
					// when we found ourself, the current is the next image
					if ( foundSelf ) {
						next = getInfo(image, "next", "Next &gt;");
						// stop searching
						break;
					} else {
						// didn't find ourself yet, so this may be the one before ourself
						prev = getInfo(image, "prev", "&lt; Prev");
					}
				}
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// Resizing large images
			var pagesize = TB_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			// TODO don't use globals
      if(imageGroup.length > 1) { 
        TB_WIDTH = imageWidth + 30 + 76 + 18;
        TB_HEIGHT = imageHeight + 60; 
        // Browser detection is bad and all, but hey, its better than things not working
        if(jQuery.browser.msie) {
          TB_HEIGHT += 30; 
          if(navigator.appVersion.match(/MSIE\s6\.0/) == "MSIE 6.0") {
            TB_WIDTH += 20;
					}
				}
        
        // make additional image links and containing div
        thumbPreloader = Array();
        additional_links = "<div id='TB_additional_images'>";
        var thumb_x = 76;
        var thumb_y = imageHeight;
        
        for (var i = 0; i < imageGroup.length; i++) {
          var image = imageGroup[i];
          // look for ourself
          var image_selected = "";
          if ( image.href == url ) {
            image_selected = "class='TB_Selected'";
            }
            
          thumbPreloader[i] = new Image();
          thumbPreloader[i].onload = function() {
            //thumbPreloader[i].onload = null;    
					}  
        thumbPreloader[i].src = image.href;
        var thumbImgWidth = thumbPreloader[i].width;
        var thumbImgHeight = thumbPreloader[i].height;
        if (thumbImgWidth > thumb_x) {
          thumbImgHeight = Math.floor(thumbImgHeight * (thumb_x / thumbImgWidth)); 
          thumbImgWidth = Math.floor(thumb_x); 
          if (thumbImgHeight > thumb_y) { 
            thumbImgWidth = Math.floor(thumbImgWidth * (thumb_y / thumbImgHeight)); 
            thumbImgHeight = Math.floor(thumb_y); 
					}
				}
				if(thumbImgWidth < 1) {
          thumbImgWidth = thumb_x;				
				}
				
				if(thumbImgHeight < 1) {
          thumbImgHeight = 60				
				}
				
				if(jQuery('img',image).attr('src') == null) {
					image_src = jQuery(image).attr('rev');
				} else {
					image_src = jQuery('img',image).attr('src');
				}
				
				image_src = image_src.replace(/width=(\d)*/, "width="+thumbImgWidth);
				image_src = image_src.replace(/height=(\d)*/, "height="+thumbImgHeight);
        additional_links += "<a href='#' "+image_selected+" id='TB_ThumbnailLink_"+i+"' ><img class='TB_Thumbnail_Image' src='"+image_src+"' width='"+thumbImgWidth+"' height='"+thumbImgHeight+"' alt=''/></a>";
        }
        
        additional_links += "</div>";
       jQuery("#TB_window").append("<div id='TB_Header'><div id='TB_TopCloseAjaxWindow'><a href='#' id='TB_TopCloseWindowButton' title='Close'>close</a></div>"+imageTitle+"</div>");
        
        jQuery("#TB_window").append(additional_links);
        jQuery("#TB_TopCloseWindowButton").click(TB_remove);
        }
        else
          {
          TB_WIDTH = imageWidth + 30;
          TB_HEIGHT = imageHeight + 60;
          }
			// TODO empty window content instead
			jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + imageCount + prev.html + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>");
			
			jQuery("#TB_closeWindowButton").click(TB_remove);
   
      function buildClickHandler(image) {
         return function() {
            jQuery("#TB_window").remove();
            jQuery("body").append("<div id='TB_window'></div>");
            TB_show(image.caption, image.url, rel);
            return false;
          };
       }   
      
      if(imageGroup.length > 1)
        {  
        goImage = Array();
        for (var i = 0; i < imageGroup.length; i++) {      
          goImage[i] = buildClickHandler(getInfo(imageGroup[i], "image_"+i+"", ""));
          jQuery("#TB_ThumbnailLink_"+i+"").click(goImage[i]);
          }
        }
			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ( prev.html ) {
				jQuery("#TB_prev").click(goPrev);
			}
			
			if ( next.html ) {		
				jQuery("#TB_next").click(goNext);
			}
			
			// TODO use jQuery, maybe with event fix plugin, or just get the necessary parts of it
			document.onkeydown = function(e) {
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				switch(keycode) {
				case 27:
					TB_remove();
					break;
				case 190:
					if( next.html ) {
						document.onkeydown = null;
						goNext();
					}
					break;
				case 188:
					if( prev.html ) {
						document.onkeydown = null;
						goPrev();
					}
					break;
				}
			}
			
			// TODO don't remove loader etc., just hide and show later
			TB_position();
			jQuery("#TB_load").remove();
			jQuery("#TB_ImageOff").click(TB_remove);
			
			// for safari using css instead of show
			// TODO is that necessary? can't test safari
			jQuery("#TB_window").css({display:"block"});
		}
		imgPreloader.src = url;
		
	} else { //code to show html pages
		//alert(url);
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery( queryString );
		
		TB_WIDTH = (params['width']*1) + 30;
		TB_HEIGHT = (params['height']*1) + 40;

		var ajaxContentW = TB_WIDTH - 30,
			ajaxContentH = TB_HEIGHT - 45;
		
		if(url.indexOf('TB_iframe') != -1){				
			urlNoQuery = url.split('TB_');		
			jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='TB_showIframe()'> </iframe>");
		} else {
			jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");
		}
				
		jQuery("#TB_closeWindowButton").click(TB_remove);
		
			if(url.indexOf('TB_inline') != -1){	
				jQuery("#TB_ajaxContent").html(jQuery('#' + params['inlineId']).html());
				TB_position();
				jQuery("#TB_load").remove();
				jQuery("#TB_window").css({display:"block"}); 
			}else if(url.indexOf('TB_iframe') != -1){
				TB_position();
				if(frames['TB_iframeContent'] == undefined){//be nice to safari
					jQuery("#TB_load").remove();
					jQuery("#TB_window").css({display:"block"});
					jQuery(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
				}
			}else{
				jQuery("#TB_ajaxContent").load(url, function(){
					TB_position();
					jQuery("#TB_load").remove();
					jQuery("#TB_window").css({display:"block"}); 
				});
			}	
	}
	
	jQuery(window).resize(TB_position);
	
	document.onkeyup = function(e){ 	
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}
		if(keycode == 27){ // close
			TB_remove();
		}	
	}
		
}

//helper functions below

function TB_showIframe(){
	jQuery("#TB_load").remove();
	jQuery("#TB_window").css({display:"block"});
}

function TB_remove() {
 	jQuery("#TB_imageOff").unbind("click");
	jQuery("#TB_overlay").unbind("click");
	jQuery("#TB_closeWindowButton").unbind("click");
  jQuery("#TB_TopCloseWindowButton").unbind("click");
	jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').remove();});
	jQuery("#TB_load").remove();
	return false;
}

function TB_position() {
	var pagesize = TB_getPageSize();	
	var arrayPageScroll = TB_getPageScrollTop();
	var style = {width: TB_WIDTH, left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2), top: (arrayPageScroll[1] + (pagesize[1]-TB_HEIGHT)/2)};
	jQuery("#TB_window").css(style);
	jQuery("#TB_window").css("margin-top", 0);
}

function TB_overlaySize(){
	if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {	
		yScroll = window.innerHeight + window.scrollMaxY;
		xScroll = window.innerWidth + window.scrollMaxX;
		var deff = document.documentElement;
		var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
		var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
		xScroll -= (window.innerWidth - wff);
		yScroll -= (window.innerHeight - hff);
	} else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
		xScroll = document.body.scrollWidth;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		yScroll = document.body.offsetHeight;
		xScroll = document.body.offsetWidth;
  	}
	jQuery("#TB_overlay").css({"height": yScroll, "width": xScroll});
	jQuery("#TB_HideSelect").css({"height": yScroll,"width": xScroll});
}

function TB_load_position() {
	var pagesize = TB_getPageSize();
	var arrayPageScroll = TB_getPageScrollTop();
	jQuery("#TB_load")
		.css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2), top: (arrayPageScroll[1] + ((pagesize[1]-100)/2)) })
		.css({display:"block"});
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}

function TB_getPageScrollTop(){
	var yScrolltop;
	var xScrollleft;
	if (self.pageYOffset || self.pageXOffset) {
		yScrolltop = self.pageYOffset;
		xScrollleft = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){	 // Explorer 6 Strict
		yScrolltop = document.documentElement.scrollTop;
		xScrollleft = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScrolltop = document.body.scrollTop;
		xScrollleft = document.body.scrollLeft;
	}
	arrayPageScroll = new Array(xScrollleft,yScrolltop) 
	return arrayPageScroll;
}

function TB_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

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;
    }
};
(function($){
$.extend({
  jYoutube: function( url, size ){
    if(url === null){ return ""; }

    size = (size === null) ? "big" : size;
    var vid;
    var results;

    results = url.match("[\\?&]v=([^&#]*)");

    vid = ( results === null ) ? url : results[1];

    if(size == "small"){
      return "http://img.youtube.com/vi/"+vid+"/2.jpg";
    }else {
      return "http://img.youtube.com/vi/"+vid+"/0.jpg";
    }
  }
});
})(jQuery);
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
//EOF

