var browser
var auto
//########################################################################################################
//returns the name of the current browser
//use the variable => browser to check the current browser
var css_browser_selector = function() 
{var ua=navigator.userAgent.toLowerCase(),
	is=function(t){return ua.indexOf(t) != -1;},
	h=document.getElementsByTagName('html')[0],
	b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('chrome')?'chrome webkit safari':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js'; 
	h.className += h.className?' '+c:c;
	browser = b
	}();
	
//$(window).load(function () {	})

//$('#q').bind('keyup', function (event) { quick_search.get(event.keyCode, this) })


//$('#cat_nav_no_js').remove()
//$('#mainCatNav').show()

//init_nav()
//$('#electronics, #cameras, #fashion, #footwear, #household, #computers, #auto, #recreation, #gifts').bind('mouseover', function(){nav_move(this.id)})
//$('#cat_nav').bind('mouseover', function (e) { $('#outCatNavCont').stop() }).bind('mouseout', function (e){fixOnMouseOut(this, e, 'closeNav()')} )
//$('#cat_nav-container').bind('mouseout', function (e) { fixOnMouseOut(this, e, 'closeNav()') })

	// $('#q').bind('keyup', function (event) { autoComplete.input($(this).val(), event.keyCode) })
	// autoComplete.init()
//})

var quick_search = function () {
	return{
		get 	: function (keyCode, value)	{
			
		},
		show 	: function ()	{
			alert("value")
		}  
	}
}()



var initialize = function(){
	return {
		itemPage : function(sub_cat_name, main_cat_name){
				$('#zoomL').fancyZoom({scaleImg: true, closeOnClick: true});
				$('#zoomL').click(function () { pageTracker._trackPageview("/Item_Page/View_Larger_Image") })
			//h1 Reposition
			//$("#itemHeader").appendTo("#shipping_item_page_banner").css({position: 'relative', zIndex: 1})
			
			// Add mouseover events to alternate images if they exist <= show_item page
			$('.altImageold').bind("mouseover", function(e){
				swapImg(this.id)
			})
			
			// Add click events to product summary and reveiw tabs  <= show_item page
			$('#ps, #rv').bind("click", function(e){ 
				if (this.className != 'selected'){
					$(".selected").toggleClass("not_selected") //takes tab w/class selected and adds not_selected class
					$(this).toggleClass(this.className).toggleClass("selected") //adds class selected to the "clicked" tab
					var old_tab = (this.id == 'rv')? "ps_content" : "rv_content" //gets the old last opened tab
					$("#"+old_tab).hide() 
					$("#"+this.id+"_content").show()
				}
			});
			
			$('#commit').bind("click", function() {return verify()})
			//Add click event to show review link to fade in review <=show_item page
			
			//Adds event for to show review form
			$('#show_review').bind("click", openReview)
			
			$('#rc').bind("click", cS.cancel)
			
			//adds events for stars on review form
			$('.revStar').bind("mouseover", 
											function () { cS.add(this) 
								 }).bind("click", 
											function () { cS.confirm(this) 
								 }).bind("mouseout", 
											function () { cS.remove(this) 
			})
			
			//getCarousel(sub_cat_name, main_cat_name);
			
			$("#var_id").bind("change", function () {
				
				var windowLoc = String(window.location)
				//var tempString = "\d{"+this.value+"}"
				//alert(tempString)
				//var myregexp = new RegExp(tempString)
				windowLoc = windowLoc.replace(/\d{5}/, this.value)
				window.location=windowLoc
				
				
			})
			
			
			//fixes breadcrumbs in ie6 so they dont go behind menues
			fixPadding();
			$('#prop65').click(function () { $(this).fadeOut(100) ; $('#propSpan').fadeIn(100) })
			
		},
		tilesPage : function(){
					fixPadding(true);
		},
		saveInfoPage : function(){
				$(document).ready(function() {
					
      	});
				$('.saveOno').bind("change", function (e){
					save_info(this.checked, this.id)
				}).click(function () { this.blur() } )
		},
		homePage : function(){
					// var no = param.authenticity_token
					// at = "authenticity_token="+no.value
					// $.ajax({
					// 	type: "POST",
					// 	url: "/customer/login?from_checkout=true",
					// 	data: $(param).serialize(),
					// 	async: true,
					// 	success: function (msg){
					// 		get_account_info(msg,  at)
					// 	}
					// })
		},
		invitePage : function () {
			$('#create_link_form').bind('submit', function (e) {
				$('#link_errors').fadeOut(200)
				$.ajax({
					type: "POST",
					url: "/customer/update_invite_link",
					data: $(this).serialize(),
					async: true,
					success: function (data){
						if(data === 'false'){
							$('#link_errors').text("Sorry that url is unavailable.").fadeIn(500)
						}
						else{
							$('#url, #submit_link').hide()
							$('#personal_link').css('width', '100%').append(data)
						}
					}
				})
				return false
			})
			
				
			$('#send_emails').bind('submit', function (e) {
				$('#send_in_progress').css({zIndex:1, opacity: '0.7'})
				var emailForm = $(this)
				if ( emailForm.serialize().match(/\+email\+addresses\.\+For\+example/) === null && emailForm.find("#email_list").val().match(/@/) != null ){ 
					$.ajax({
						type: "POST",
						url: "/customer/invite_ajax",
						data: $(this).serialize(),
						async: true,
						success: function (data){
							$('#email_list').val('')
							var messages = eval(data)
							if (messages.length > 0){
								add_row(0, messages)
							}
						$('#send_in_progress').css({zIndex:-1})
						}
					})
				}
				else{
					just_kidding($("div#send_in_progress H1"), "send")
				}
				return false
			})
			

			
			$('#resend_invites').bind('submit', function (e) {
				//$('#link_errors').fadeOut(200)
				$('#update_in_progress').css({zIndex:1, opacity: '0.7'})
				console.log($(this).serialize().match(/email/))
				if ($(this).serialize().match(/email/)){
					$.ajax({
						type: "POST",
						url: "/customer/invite_ajax",
						data: $(this).serialize(),
						async: true,
						success: function (data){
							$('#update_in_progress').css({zIndex:-1})
							var messages = eval(data);
							if (messages.length > 0){
								update_row(0, messages)
							}
						},
						complete: function () {
							$('.email_cb').attr('checked', false)
						}
					})
				}
				else
				{
					just_kidding($("div#update_in_progress H1"), "resend")
				}
				return false
			})
			
			$('#oi').click(function () {
				$('#invites_wrapper').animate({left: '0px'}, 300)
			})
			$('#ai').click(function () {
				$('#invites_wrapper').animate({left: '-935px'}, 300)
			})

			$("#selectAll").click(function (e){
				var checked = ($(this).attr("checked") == true)? "checked" : false
				$('.email_cb').attr("checked", checked)
			})
		},
		registerPage : function(){
			
		},
		cartPage : function (){
			$(document).ready(function() {
				
      });
		},
		accountPage : function(){
			$(document).ready(function() {
				
      		});
			
			$('#sameAsBilling').bind("change", function() { cloneValues(this.checked)}).click(function () { this.blur() } )
		},
		checkoutPage : function(){
			$(document).ready(function() {
				
				$("#clear_bf_bucks").click(function (e){
					//empty BF Bucks fields
					$("#fm_bb_ser_num,#fm_bb_pin").val('')
				})
				
				$('#main_submit').click(function () {$(this).hide()})			
				
				$('#order_attr_bill_zip, #order_attr_ship_zip, .numbers').bind('keypress', function (event) {return isNumberKey(event)})
				
     });
			field_with_errors()
			$('#sameAsBilling').bind("change", function() {cloneValues(this.checked)}).click(function () { this.blur() } )
		},
		noonerPage : function (){
			var x = $('#slideshow_inner')
						x.innerfade({
							speed: 500,
							timeout: 1000,
							type: 'sequence',
							containerheight: '400px'
						});
						//setupZoom()
				// $$('img.altImageold').each(function(obj){
				// 			addEvent(obj, 'mouseover', function () { swapImg(obj.id, obj.name) })
				// 		;});
				$(document).ready(function() {
					//iePngFix();
	      });
		},
		confirmOrder : function (){
			$(document).ready(function () {
				var AOholder;
				showAO()
			})
		}
	}
}();

function just_kidding(obj, action){
	setTimeout(function() {
		nextText = (action === "send")? "No Valid Emails Found" : "No Emails Selected"
		$(obj).text(nextText)
		setTimeout(function() { 
			$(obj).text("Sending Emails").parent().css({zIndex:-1})
		}, 900);
	}, 600);
}

function update_row(index, array){
		var obj = array[index]
		if (obj.sent === true){
			var li = $('#'+obj.id)
			$(li).prev().text(parseInt($(li).prev().text()) + 1)
			$(li).parent().animate({backgroundColor: "#1DBB02"}, 100, function (){
				$(this).find("li:last-child").html("Sent!")
				$(this).find("li.last_updated").html("Just Now!")
				if (index != array.length - 1){
					update_row(index+1, array)
				}
			}).animate({backgroundColor: "#CECECE", color: "#1DBB02"}, 100)
		}
		else{
			var li = $('#'+obj.id)
			$(li).parent().animate({backgroundColor: "#BB0210"}, 100, function (){
				$(this).find("li:last-child").html("Not Sent! you can only send 1 invite in 24hours");
				if (index != array.length - 1){
					update_row(index+1, array)
				}
			}).animate({backgroundColor: "#CECECE", color: "#BB0210"}, 100)
		}
}

function add_row(index, array){
	var obj = array[index]
	var ul = "<ul id='ul_"+parseInt(index+tpi)+"'  style='margin: 0pt; padding: 0px; width: 100%; float: left; list-style-type: none; list-style-image: none; list-style-position: outside; height: 20px; font-size: 12px;'>"
	ul += "<li style='float: left; display: block; width: 3%; height: 20px; text-align: left; line-height: 20px;'><input type='checkbox' value='"+obj.email+"' name='email_"+parseInt(index+tpi)+"' class='email_cb'/></li>"
	ul += "<li style='float: left; display: block; width: 39%; height: 20px; text-align: left; line-height: 20px;'>"+obj.email+"</li>"
	ul += "<li style='float: left; display: block; width: 20%; text-align: left; line-height: 20px;' class='last_updated'>&nbsp;</li>"
	ul += "<li style='float: left; display: block; width: 4%; height: 20px; text-align: left; line-height: 20px;'>1</li>"
	ul += "<li style='float: left; display: block; width: 34%; height: 20px; text-align: left; line-height: 20px;' id='email_"+parseInt(index+tpi)+"'/></ul>"
	
	
	$('#email_rows').append(ul)
	
	$('#ul_'+parseInt(index+tpi)).animate({backgroundColor: "#148714"}, 150, function (){
	$(this).find("li:last-child").html("Sent!")
	$(this).find("li.last_updated").html("Just Now!")
	$('#pending_invites_count').animate({backgroundColor: "#148714"}, 100, function () { 
		$('#pending_invites_count').text(parseInt($('#pending_invites_count').text())+1).animate({backgroundColor: "#FFFFFF"}, 100) })
	
	if (index != array.length - 1){
		add_row(index+1, array)
	}
	else{
		tpi = tpi + array.length
		$('#total_p_invites').val(tpi)
	}
	}).animate({backgroundColor: "#CECECE", color: "#148714"}, 150) //400
	
}


function showAO(){
	AOholder = $('#asdf').html()
	if (browser.match(/ie/)){
		document.getElementById('aoWrap').outerHTML="  "
	}
	else{
		$('#aoWrap').remove()	
	}
	modalBox(AOholder, '693')
}

function clearTextArea() {
	var emailList = $('#email_list')
	if (emailList.val() == 'Enter friends\' email addresses. For example: johndoe@domainname.com, jane@domainname.com'){
		emailList.val('').css("color", "#1E1E1E")
	}
	//if(emailList.value=='Enter friends\' email addresses.'){emailList.value='';emailList.style.color='#1E1E1E';}
}

function fixPadding (rss) {
	x = (browser == 'ie ie6')? (rss == true)? $('.breadcrumbs, #rss').css({paddingTop: '20px'}) : $('.breadcrumbs').css({paddingTop: '20px'}) : false; eval(x)
}

//########################################################################################################
//Fixed PNG images in ie 6
function iePngFix () {
	eval((function(){var a="Oof =un_fed#{}}=#};(#!all||ƒ@a9a=parseFloZ(navigZorV@KMSIE (d.*)/)[1](a5.5)||(a>=7)9==0#bodyendChild(style))}[-1].addRul`.,':absolute;z-_xzIn_xtƒTƒleftLefthjHjw¬W¬~:exp8sK(progid:DXIGTransform.Microsoft.A√IGLoad@(src='+this.nextSiblg.src.8place(/'/g,%27)+')U'=b6~=a√(ƒacity=0)¡c=divUc.classNamq;b.^stZic¿6=8lZive}b.pa8ntNo_.s@tBefo8(c,bcP¡b=[],c,d,e,f¡gmgUgQgY}hnputUhqhY;e.O&&e.O^iG¿#Qe}}bqbY¡i=e.getAttribut`sm:iepngU!i#contue}switch(i#3no:3false:30:b8ak;_fault:(e)}}a=b=c=d=qf=g=hP)(.v@K=1.4;.8leasqnew DZ`Jan 1, 2007)",b=50;while(b>=0)a=a.replace(new RegExp("#3689@GKOPQUYZ_`jq~¿¡¬√ƒ".charAt(b),"g"),("\\\042\074\n\044:expression(this.nextSibling.ScriptingMagic.fixPNGdocument..length=getElementsByTagName(istyleSheets;cd;c++){offsetfor(c=0,d=sm-iepng-backdropfunction(createElement(var .match(/ScriptingMagic=position);currentStyle.if(window.){case #b.style.re#8turn}ermagesiontype=null}b[b]=[c]atdee(eighte=filt@in/i).app;idthlphaop".split(""))[b--]);return a})());
}

function isNumberKey(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
   return false;
   return true;
}



//########################################################################################################
//TODO:// Comment this later
//Used on the item page to swap the alt image into the main img stageing area, 
//also changes the link of the the main image to point to the new larger 500 image
//of the current alt image selected for the zoom photo
//Third param[:fromSelect] gets passed when the prod variation is changed, cuase could effect the alternate images
var CURIMG = "";

function swapImg(img){

	var mainImgCont = (mainImgCont == null)? $('#zoomL') : mainImgCont //Selects main image container, only fires once
	var hiddenImgsCont = (hiddenImgsCont == null)? $('#hidden_images') : hiddenImgsCont //Selects hidden images div, only fires once
	
	var newImg = $('#img_'+img+'_250')
	
	if (mainImgCont.children()[0].id != 'img_'+img+'_250'){
		$('.altImageold').unbind()//unbind the mouseover on the alternate image until fade is complete and is binded again after fade is complete
	mainImgCont.children().fadeOut("fast", function () {
		$(hiddenImgsCont).append(this)
		mainImgCont.append(newImg.css({display: 'block'}))
		$('.altImageold').bind("mouseover", function(e){
			swapImg(this.id)
		})
		mainImgCont[0].href = "#img_" + img
	})
	}
}

//########################################################################################################
//Used on reviews for the stars
// var changeStar = :
//				add : function = "Gets called on mouse over"
//				remove : function "Gets called on mouse out"
// 				confirm : function "Gets called on mouse click"
var cS = function (e){
	var stars = new Array
	return{
		add : function (e){ //gets called on mouse-over
		 	stars = (stars.length == 5)? stars : $('.revStar')  //Puts all of the star images into an array only if the array doesnt all ready exist
			jQuery.each(stars, function(x) { this.src = (this.id <= e.id)? "/images/show_item/star_5.gif" : "/images/show_item/star_0.gif" });
		},
		remove : function(e){ // gets called on mouse-out
			$('#review_r_rating').val(e.id)
		}, 
		confirm : function (e){ // gets called on mouse-click
			jQuery.each(stars, function(x) {
				this.src = (this.id <= e.id)? "/images/show_item/star_5.gif" : "/images/show_item/star_0.gif"
				$(this).unbind('mouseover') // Once they click on a star this removes the mouseover for all green stars
			});
			$('#review_r_rating').value = e.id //Sets the current rating if mouse is moved off star
			},
		cancel : function (x){ // gets called when review is canceled
			$('#rev_outer').hide()
			closeReview(x)
		}
		}
}();

function openReview(){
	$('#review_content, #rev_outer').show()	
	pageTracker._trackPageview("Item_Page/Open_Review")
}

function closeReview(x){
	$('#review_content').fadeOut(500, function () {
		$('.revStar').bind("mouseover", function () { cS.add(this) }) //Adds the mouse over event back onto the stars
		$(":input.review_req").val("") //Resets all the form feilds to empty
		if(x == "success"){
			$('#saved_msg').html('You submission has been received and will be reviewed and posted within 7 days.')
			setTimeout(function() {
				$('#saved_msg').slideUp("slow")
			}, 2000);
		}
	})


$('#rev_outer').fadeOut(500)

}

//########################################################################################################
function verify(){
			var err = 0	
			jQuery.each($('.review_req'), function(e) {
				err += ($(this).val() == "")? 1 :  0
			})
		if (err > 0){
			$('#error_msg').css({display: 'block', color: 'red'})
			$('#error_msg').html('Please provide all required information')
			return false;
			}

			cS.cancel("success")
			$('#show_review').unbind()
	 		return true;
}

function sendForm (param) {
	$.post("/store/review?"+$(param).serialize())
}

function sendForm2 (param){
	//$('#aoDetails').animate({top: '-480px'}, 360)
	//$('#aoWrap').animate({height: '200px'}, 360)
	$('#subTbl').fadeOut(400)
	$.post("/store/account_offer?"+$(param).serialize(), function (data) {aoResponse(data)})
}

function aoResponse(data){
	
	if (data != 'https://bfdeals.local/customer/edit'){
		//Errors 
		//$('#aoWrap').animate({height: '500px'}, 360)
		$('#subTbl').fadeIn(400)

		$('#ao_errs').html(data)
	}
	else{
		//No Errors
		pageTracker._trackPageview("/order_confirmation/account_created")
		$('#aoWrap').animate({height: '100px'})
		$('#aoInnerWrap').animate({left: '-700px'})
		$('#um_log_in').html('Log Out')
 		$('#um_register').html("My Account")
 		$('#um_log_in')[0].href = "/customer/logout"
 		$('#um_register')[0].href = "/customer/edit"
	}
}

//########################################################################################################
//Used on item pages wchich have variations with images included for 
//each variation, This changes the main image to the new variation,
//it will also update the alt_images to include the new variation image
function changeProd(vars, changeTo, changeFrom){
	var newProd
	for (var x = 0; x <= vars.length - 1; ++x) {
		if (vars[x].p_prod_int_num == changeTo){
			newProd = vars[x]
		}
	}
	var height = $('#image'+changeFrom).css('height')
		$('#zoomL').children().hide()
		$('#zoomL').append("<img src=http://hlaimages2.heartlandamerica.com/prod_images/250/"+newProd.p_prod_num+".jpg / >")
		
	$('#price').html('$'+newProd.p_price1)
	
}
//########################################################################################################
//Appends a red * to the end of anyfield with an error on the checkout page
function field_with_errors(){	
	fields = $('.fieldWithErrors')
	$.each(fields, function(){
		$(this).append($(this).next().css({color: 'red', fontSize: '18px'}))
	})
}
//########################################################################################################
//Used on the account edit page and also on the checkout page to 
//copies form fields with the billing class to fields with the shipping class
function cloneValues(checked){
	var billing = [], shipping = []
	
	$('.billing_field').each(function (e){
		billing[e] = $(this).val()
	})
	
	$('.shipping_field').each(function (e){
		text = (checked == true)? billing[e] : ""
		$(this).val(text)
	})
	
}
//########################################################################################################
function sendLogin (param) {
	// var no = param.authenticity_token
	// at = "authenticity_token="+no.value
	// $.ajax({
	// 	type: "POST",
	// 	url: "/customer/login?from_checkout=true",
	// 	data: $(param).serialize(),
	// 	async: true,
	// 	success: function (msg){
	// 		get_account_info(msg,  at)
	// 	}
	// })
}

function getCarousel(scn, mcn) {
	// $.ajax({
	// 	type: "GET",
	// 	url: "/store/getCarousel",
	// 	data: "sub_name="+scn+"&main_name="+mcn,
	// 	async: true,
	// 	success: function(hz_car){
	// 		$('#hz_car_cont').html(hz_car)
	// 		$("#myController").jFlow({
	// 			slides: "#mySlides",
	// 			controller: ".jFlowControl",  
	// 			slideWrapper : "#jFlowSlide",  
	// 			selectedWrapper: "jFlowSelected",   
	// 			width: "870px",
	// 			height: "250px",
	// 			duration: 600,
	// 			prev: ".jFlowPrev",  
	// 			next: ".jFlowNext",
	// 			auto: false
	// 		});
	// 		if ($('#features')[0] == null){
	// 			// $('#hz_car_cont').animate({ 
	// 			// 					marginTop: "-20px"
	// 			// 				}, 700 );
	// 		}
	// 	}
	// })
}




//########################################################################################################
function get_account_info (res, at) {
		if (res != ""){
			login_errors(res)
		}
		else
		{		
			var nh = $('#checkout_wrapper').css('height')
		
			$('#footerMsg').hide()
			$('#checkout_wrapper').css({height: nh, display: 'block'})
			$('#checkout_content').hide()
			$('#loader_div').css({display: 'block'})
			
			
			$.ajax({
				type: "POST",
				url: "/store/checkout", 
				data: at,
				success: function(arg){
				  	$('#um_log_in').html('Log Out')
			 						$('#um_register').html("My Account")
			 						$('#um_log_in')[0].href = "/customer/logout"
			 						$('#um_register')[0].href = "/customer/edit"
			 						$('#main_content').html(arg)
			 						$('#footerMsg').show()
				}
			})
			
	}
}
//########################################################################################################
function login_errors(arg) {
	if(arg != ""){
 		$('#loginErrors').html(arg).slideUp(150, function(){
			$('#loginErrors').slideDown(400)
		})
	}
}

//########################################################################################################
//Fades columns on save_info page for columns that should not be saved
function save_info(val, tbl){
	if(val == false){
		$(tbl).fadeTo("normal", 0.2)
	}
	else{
		$(tbl).fadeTo("slow", 1)
	}
}

//########################################################################################################
//shows and hides shipping details for slot machines
function ship_details(close)
{
	$('#ship_details').html("<div id='closeShp' style='cursor: pointer; background-color:#cdcdcd;'>CLOSE</div>Buyer is responsible for checking state and local laws prior to purchase. We make no representation as to the legality of the use of any machine in any particular state. We are not responsible for machines used for any purpose inconsistent with state and local laws, or for machines that have been altered or relocated to a state whose regulations limit or ban the ownership of such equipment. We reserve the right to refuse sale and/or sales of any machine to anyone at our discretion. Wuyer agrees that by purchasing any of the machines listed on this site, you will not use them for the purpose of gambling or commercial use. the buyer, if executing any activity deemed illegal in their state will hold the seller harmless and in addition agrees to defend at the buyers' expense any and all adverse claims made against the seller. <br /> Not available in these states: AL, CA, CO, CT, FL, HI, IN, LA, NE, NJ, NM, OR, SC, TN, WA")
	$('#ship_details').show()
	
	$('#ship_details').css({visibility: 'visible'})
	$('#closeShp').bind('click', function () { ship_details('close')})

	if (close){
		$('#ship_details').hide()
	}
}

function closePopUp(){
	modalBox()
}

//########################################################################################################
//Bind an object and servaral args to a method
(function($){
$.bind = function(object, method){
	var args = Array.prototype.slice.call(arguments, 2);
	return function() {
		var args2 = [this].concat(args, $.makeArray( arguments ));
		return method.apply(object, args2);
	};
};
})(jQuery);

(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);


var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
function modalBox(content, width, callback) {
	if(!content){
		if (browser.match(/ie/)){
			document.getElementById('ntz_modal').outerHTML="  "
			$('#ntz_overlay').fadeOut(function(){document.getElementById('ntz_overlay').outerHTML="  "});
		}
		else{
			$('#ntz_modal').remove()
			$('#ntz_overlay').fadeOut(function(){this.remove()});
		}
		
		try{if(IE6){$('body').find('select.unhideThis').removeClass('unhideThis').visibility('visible');}}catch(err){};
		$('embed.unhideThis, object.unhideThis').removeClass('unhideThis').css('visibility', 'visible');
		return false;
	}
	try{if(IE6){$('body').find('select:visible').addClass('unhideThis').visibility('hidden');}}catch(err){};
	$('embed:visible, object:visible').addClass('unhideThis').css('visibility', 'hidden');
	$('body').append('<div id="ntz_overlay"></div>');
	$('#ntz_overlay').css({
		width		:	'100%',
		height		:	$(document).height(),
		position	:	'absolute',
		left		:	0,
		top		:	0,
		backgroundColor	:	'#000000',
		zIndex		:	9990,
		opacity		:	0
	}).fadeTo(200, 0.5);
	$('body').append('<div id="ntz_modal"></div>');
	$('#ntz_modal').css({
		border		:	'1px solid #2d7abb',
		width		:	width ? width : 350,
		backgroundColor	:	'#FFFFFF',
		position	:	'absolute',
		left		:	'50%',
		top		:		'25%',
		zIndex		:	9995,
		marginLeft	:	-(Math.ceil((width ? width : 800)/2))
	}).append(content);
	//$('#aoWrap').fadeIn(400)
	$('#ntz_modal a:eq(0), #ntz_modal input, #ntz_modal textarea').focus();
	try{
		callback.call();
	}catch(err){};	
};

jQuery.extend( jQuery.easing,
{
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	}
});

function is_child_of(parent, child) {
			if( child != null ) {			
				while( child.parentNode ) {
					if( (child = child.parentNode) === parent ) {
						return true;
					}
				}
			}
			return false;
		}
		
function fixOnMouseOut(element, event, JavaScript_code) {
	var current_mouse_target = null;
	if( event.toElement ) {				
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {				
		current_mouse_target 			 = event.relatedTarget;
	}
	if( !is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
		eval(JavaScript_code);
	}
}
