jQuery.noConflict();

jQuery(function(){
		/**
		 * Image preloader.
		 */
		var current_image;

		jQuery([

			image_api.get_base_image_url('nav/nav_brands_hover.jpg'),
			image_api.get_base_image_url('nav/nav_categories_hover.jpg'),
			image_api.get_base_image_url('nav/nav_licensing_hover.jpg'),
			image_api.get_base_image_url('nav/nav_brands.jpg'),
			image_api.get_base_image_url('nav/nav_categories.jpg'),
			image_api.get_base_image_url('nav/nav_licensing.jpg')

		]).each(function(){
			current_image = new Image();
			current_image.src = this;
		})
})

var bannerslide = 0;
var altused = "";
function divToolTipShow(element){
	$('divToolTip').innerHTML = element.getAttribute('tooltip');
	$('divToolTip').style.display="block";
}
function divToolTipHide(){
	$('divToolTip').style.display="none";
}

// This will display the quick look icon over the product image
function show_Quick_Look(element, view) {
	if(view == 'grid' || view == 'search')
		jQuery(element).css({'position' : 'absolute', 'top' : '30px', 'right' : '55px', 'z-index' : '9999'}).fadeIn(300);
	else if(view == 'list')
		jQuery(element).css({'position' : 'absolute', 'top' : '30px', 'right' : '5px', 'z-index' : '9999'}).fadeIn(300);
}

function hide_Quick_Look(obj) {
	jQuery(obj.quicky).stop(false,true);
	jQuery(obj.quicky).fadeOut(200);
}

function quick_look(prodId) {
	var scrollTop = jQuery(window).scrollTop() + 40;
	new Ajax.Updater('quick-look-info', '/ajax/getQuickLook', {
		method : 'GET',
		asynchronus : true,
		parameters : {prodId : prodId},
		onComplete : function(response) {
			jQuery('#quick-look-popup').css({'display' : 'block', 'position' : 'absolute', 'z-index' : '99999', 'top' : scrollTop+'px', 'left' : '315px'});
		}
	});
}

function menuSlide(selected) {
/*
 * This is the code that handles the sliding effect of the menu.
 * It takes a dom object (usually 'this') for the selected menu
 * and compares it to all the other menu options, setting their
 * states as necessary.
 */
session = new Session;
session._SetSessionData("selected_menu",selected.id);
effect_array = new Array();

 var elements = $('right-container').childElements();
 elements.each(
 	function(value) {
 		value2 = value.down();
 		if (value2 == selected) {
 			if (value2.down().hasClassName("unselected")) {
				value2.down().removeClassName("unselected");
			}
			if (!value2.down().hasClassName("selected")) {
				value2.down().addClassName("selected");
				effect_array.push(new Effect.BlindDown(value2.next(),{transition: Effect.Transitions.linear, sync: true}));
			}

 		} else {
			if (value2.down().hasClassName("selected")) {
				value2.down().removeClassName("selected");
				effect_array.push(new Effect.BlindUp(value2.next(),{transition: Effect.Transitions.linear,  sync: true}));
			}
			if (!value2.down().hasClassName("unselected")) {
				value2.down().addClassName("unselected");
			}
 		}
 	});
 	new Effect.Parallel(effect_array,{duration: .3});
	return true;
}

function eraseCookie(cookie_info) {
	cookie_info.each(function(i){
	new Ajax.Request('/ajax/eraseCookie',{ asynchronous: false, parameters: { cookie_name: i.key, cookie_email: i.value}});
	});
	window.location.reload();
}

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function is_object( mixed_var ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://crestidg.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

function nextObject(n) {
//	var n = this;
	do n = n.nextSibling;
	while (n && n.nodeType != 1);
	return n;
}

function previousObject(p) {
//	var p = this;
	do p = p.previousSibling;
	while (p && p.nodeType != 1);
	return p;
}

var CustomSlide = Class.create({
	initialize: function(element) {
		var inner_element = element.down();
		inner_element.style.position = 'relative';
		inner_element.style.top = element.getHeight()*.80 + "px";
		inner_element.style.left = element.getWidth()*-1 + "px";
		this.parameters = {delay: .2};
		this.element = element;
		this.inner_element = inner_element;
	},
	moveLeft: function() {
		Effect.MoveBy(this.inner_element, 0, this.element.getWidth(), {duration: this.parameters.delay, afterFinish: this.moveUp(), queue: 'front'});
	},
	moveUp: function() {
		Effect.MoveBy(this.inner_element, this.element.getHeight()*.80*-1, 0,  {duration: this.parameters.delay, queue: 'end'});
	},
	moveDown: function() {
		Effect.MoveBy(this.inner_element, this.element.getHeight()*.80, this.element.getWidth(), {duration: this.parameters.delay, afterFinish: this.moveUp(), queue: 'front'});
	}

});

var Popup = {
	onClick: function (event) {
		var target = $('popup-outer');
		var target2 = $('popup-inner');
		Popup.populatePopup(target2,this.readAttribute('value'),this.readAttribute('type'));
		target2.observe('mouseout', Popup.onMouseOut.bindAsEventListener(this));

		offset = this.cumulativeOffset();
		posX = offset.left;
		posY = offset.top;

		target.style.top = posY+"px";
		target.style.left = posX+"px";
		if ((Prototype.Browser.IE) || (Prototype.Browser.Opera)) {
			if ($('shipping-ie-hack')) {
				$('shipping-ie-hack').hide();
			}

		} else {
			slide = new CustomSlide(target);
		}

		target.show();

		if ((Prototype.Browser.IE) || (Prototype.Browser.Opera)) {

		} else {
			slide.moveLeft();
		}
	},
	onMouseOver: function (event) {

	},
	onMouseOut: function (event) {

		if (Prototype.Browser.IE) {
			if ($('shipping-ie-hack')) {
				$('shipping-ie-hack').show();
			}
		}

		var target = $('popup-outer');
		var target2 = $('popup-inner');
		if (event.pageX || event.pageY) {
			posX = event.pageX;
			posY = event.pageY;
		} else if (event.clientX || event.clientY) {
			posX = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
			posY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
		}
		if (posX < target2.cumulativeOffset().left || posX > target2.cumulativeOffset().left + target2.getWidth() || posY < target2.cumulativeOffset().top || posY > target2.cumulativeOffset().top + target2.getHeight()) {
			target.stopObserving('mouseout', this);
			target2.stopObserving('mouseout', this);
			target.hide();
			target2.innerHTML = '';
		}
	},
	populatePopup: function(target,value,type) {
		result = function(transport) {
			this._responseText = transport.responseText;
		}
		request = new Ajax.Updater(target, '/product/getPopupInfoText/' + value + '/' + type, {
			asynchronous: false,
			onComplete: result.bind(this)
		});
	}

};

function closePopup() {
	$('popup-outer').hide();
}

function logout() {
	session = new Session;
	session._unsetSessionData();
}

function forgotPassword(message, email, cart) {
	cart = typeof(cart) != 'undefined' ? cart : false;
	template = "message";
	if (email.empty()) {
		message = "Please provide an email address.";
		template = "forgot_password";
	} else if (!email.match(/^[\d\w.-]+?[@]{1}?([\d\w-]+?[.]{1}[\w\d]+?)+?$/)) {
		message = "Invalid email address, please try again.";
		template = "forgot_password";
	} else if (!testIfEmailAddressInDb(email)){
		message = "Sorry, but we were unable to locate an account associated with that email address, please enter another email address and try again.";
		template = "forgot_password";
	} else {
		message = "An email to reset your password has been sent to you and should appear in your inbox momentarily. If you do not receive the email, please check your spam filter settings and make sure the email you provided is the one we have on file.";
	}
	if(cart){
		var tempsend = 'true';
	}else{
		var tempsend = 'false';
	}
	showGraybox(template,{message_title: 'Forgot Password', message: message, email: email, cart: tempsend});
	var customer_information = new CustomerInformation;
	customer_information._sendForgotPassword(email, cart);
}

function giftCardBalance(){
	template = "giftcardbalance";
	showGraybox(template,{message_title: 'Gift Card Balance'});
}

function getGiftCardBalance(num, cvv, fromcart){
	if(typeof fromcart == 'undefined'){
		fromcart = 0;
	}
	if(num != "" && num != null && cvv != "" && cvv != null){
		new Ajax.Updater('balance', '/ajax/getGiftCardBalance/' + num + '/' + cvv, {
			asynchronous: false,
			 onSuccess: function(transport){
				if(transport.responseText != "Invalid Card"){
					$('balance').innerHTML = "Balance is: $"+(parseFloat(transport.responseText).toFixed(2));
				}
				if(fromcart){
					$('apply-grey-hidden').style.display = "block";
					$('gift_card_number').value = num;
					$('gift_card_cvv').value = cvv;
					applyDisorNot($('gift_card_number'), $('gift_card_apply'));
					$('get_balance').setStyle({
						float: "left",
						marginLeft: "50px"
					});
					$('get_balance').up().setStyle({
						paddingBottom: "10px"
					});
				}
			}
		});
	}else{
		if (!$('balance').empty) {
			$('balance').innerHTML = "Please Enter A Card Number And CVV";
		}
	}
}
function testIfEmailAddressInDb(email) {
	var custom_form = new CustomForm();
	custom_form.verifyCustomerEmailExists(email);
	return custom_form._responseText;
}

function emailToAFriend(product_id, your_name, your_email, friend_name, friend_email, comments) {
	//Set default message and template
	message = "<div style='font-size:24px; font-weight:bold;'>Email a Friend</div><hr><input type='hidden' id='product_id' value='"+ product_id +"'>";
	template = "email_friend";
	// If the graybox has been shown yet
	if (your_name != undefined) {
		// If all of the fields are filled out or not
		if (your_name.empty() || your_email.empty() || friend_name.empty() || friend_email.empty()) {
			message = message + "<div style='color:#f00; font-size:12px;'>* Please fill out all required fields</div>";
		} else {
			if (hasValidEmail(your_email) == false) {
				message = message + "<div style='color:#f00; font-size:12px;'>Invalid email address (yours)</div>";
			} else if (hasValidEmail(friend_email) == false) {
				message = message + "<div style='color:#f00; font-size:12px;'>Invalid email address (friend)</div>";
			} else {
				template = "message";
				message = "<div style='font-size:24px; font-weight:bold;'>Email a Friend</div><hr><div>Thank you for telling your friend about SoftwareMedia.com</div>";
				emailFriend({product_id: product_id, your_name: your_name, your_email: your_email, friend_name: friend_name, friend_email: friend_email, comments: comments});
			}
		}
	}
	showGraybox(template, {message_title: "Email a Friend", message: message, product_id: product_id, your_name: your_name, your_email: your_email, friend_name: friend_name, friend_email: friend_email, comments: comments});
}
function testamonialShow(){
	//Set default message and template
	message = "<div style='font-size:24px; font-weight:bold;'>Your Testamonial</div><hr>";
	template = "customer_testamonial";
	// If the graybox has been shown yet
	if (!$('your_name')) {
		showGraybox(template, {message_title: "Your Testamonial", message: message});
	}
}
function emailFriend(parameters) {
	result = function(transport) {
		this._responseText = transport.responseText;
	}
	request = new Ajax.Request('/ajax/emailFriend', {
		asynchronous: false,
		method: 'post',
		parameters: parameters,
		onComplete: result.bind(this)
	});
}
function sendTestamonial() {
	var name = $('your_name').value;
	var company = $('your_company').value;
	var comments = $('comments').value;
	new Ajax.Request('/ajaxforstatics/emailMarkReviews', {method: 'post', parameters: {name:name,company:company,comments:comments}});
}
function submitRequestContact(){
	errors = new Array();
	var iferror = 0;
	if($('your_name').value == ''){
		errors[0] = 'Name';
		iferror++;
	}
	if($('your_phone_number').value == ''){
		errors[1] = 'Phone Number';
		iferror++;
	}
	if($('your_email_address').value == ''){
		errors[2] = 'Email Address';
		iferror++;
	}
	if($('your_poi').value == ''){
		errors[3] = 'Product(s) of Interest';
		iferror++;
	}
	if(iferror > 0){
		$('display_errors').innerHTML = "Missing Required Fields: ";
		 errors.each(function(s,i){$('display_errors').innerHTML += s;if(s != errors.last()){$('display_errors').innerHTML += ", "}});
		 $('display_errors').style.display = 'block';
	}else{
		sendRequestContact();
	}
}
function sendRequestContact() {
	var name = $('your_name').value;
	var phone_number = $('your_phone_number').value;
	var email_address = $('your_email_address').value;
	var poi = $('your_poi').value;
	var comments = $('comments').value;
	var contact_preference = "";
	if($F('your_contact_preference')){
		contact_preference = $F('your_contact_preference');
	}else if($F('your_contact_preference2')){
		contact_preference = $F('your_contact_preference2');
	}
	new Ajax.Request('/ajaxforstatics/emailRequestContact', {method: 'post', asynchronous: false, parameters: {name:name,phone_number:phone_number,email_address:email_address,poi:poi,contact_preference:contact_preference,comments:comments}});
	window.location.reload();
}
function checklarinfo(){
	errors = new Array();
	var iferror = 0;
	if($('name').value == ''){
		errors[0] = 'Name';
		iferror++;
	}
	if($('phone').value == ''){
		errors[1] = 'Phone Number';
		iferror++;
	}
	if($('email').value == ''){
		errors[2] = 'Email Address';
		iferror++;
	}
	if($('poi').value == ''){
		errors[3] = 'Product(s) of Interest';
		iferror++;
	}
	if(iferror > 0){
		$('display_errors').innerHTML = "Missing Required Fields: ";
		 errors.each(function(s,i){$('display_errors').innerHTML += s;if(s != errors.last()){$('display_errors').innerHTML += ", "}});
		 $('display_errors').style.display = 'block';
	}else{
		document.form2.submit();
	}
}

function hasValidEmail(email) {
	//Checks to see if an email address has the standard format and has a valid domain
	if (!email.match(/^[\d\w.-]+?[@]{1}?([\d\w-]+?[.]{1}[\w\d]+?)+?$/)) {
		return false;
	} else if (!function (email) {
				var custom_form = new CustomForm();
				custom_form._ValidateEmailDomain(email);
				return custom_form._responseText;
				})
	{
		return false;

	} else {
		return true
	}
}

function saveCart(response) {
	if (response.event == 'save_cart') {
		message = "Your cart has been saved and a link has been sent to you.";
		var request = new Ajax.Request("/cart/saveForLater", {
			asynchronous: false,
			method: "post",
			parameters: {email: $("email").value},
			onComplete: function (transport) {
				showGraybox('message', {message_title: 'Cart Saved', message: message});
			}
		});
	} else {
		showGraybox('cart/email',{});
		closeGraybox({event: 'save_cart',  parameters: {email: $F('email')}});
	}
}

var returnFormHandler = {
	init: function()
	{
		var e_id;

		for (e_id in {'shipSelf':1, 'airBill':1})
		{
			if ($(e_id))
			{
				$(e_id).disabled = false; // This will mess up our handlers.
				$(e_id).form.onsubmit = this.submission_handler;
			}
		}

		if ($('accept'))
			$('accept').onclick = this.click_handler;
	},
	click_handler: function()
	{
	},
	submission_handler: function()
	{
		var errors_check = returnFormHandler.verify_form();
		var error_container = $('acceptance-required');

		if (errors_check.success == true)
		{
			return true;
		}

		if (error_container.hasChildNodes())
		{
			var num_children = error_container.childNodes.length;
			for (var i=0; i < num_children; ++i)
			{
				error_container.removeChild(error_container.firstChild);
			}
		}

		for (var i=0; i < errors_check.errors.length; ++i)
		{
			var nextElement = document.createElement('li');
			nextElement.className = 'error-item';
			nextElement.innerHTML = errors_check.errors[i];
			error_container.appendChild(nextElement);
		}

		return false;
	},
	verify_form: function()
	{
		var error_list = [];

		if ($('accept').checked != true)
		{
			error_list.push('You must ackowledge that you have not activated or registered any products that you are returning.');
		}

		var reasons = {
			'list': $('accept').form.reason,
			'checked': false
		}

		for (var i = 0; i < reasons.list.length; ++i)
		{
			if (reasons.list[i].checked)
			{
				reasons.checked = reasons.list[i];
				break;
			}
		}

		if(reasons.checked != false)
		{
			if (reasons.checked.value.match(/other/i) && jQuery('input[name="reasonDetail"]').val().replace(/^\s+|[\.\|\[\]\(\)\{\}\!\@\#\$\%\^\&\*\(\)\?\.]|\s+$/, '') == '')
			{
				error_list.push('You must provide a description when choosing ' + reasons.checked.value + ' as your reason.');
			}
		}
		else
		{
			error_list.push('You must specify the reason for the return.');
		}

		var num_products = 0;
		jQuery('form input[name^=ret]').each(function()
		{
			if (this.checked)
				num_products++;
		});

		if (num_products == 0)
		{
			error_list.push('You have not selected any products to return.');
		}

		result = {'success': (error_list.length==0), 'errors': error_list};

		return result;
	}
}

jQuery(
	function()
	{
		returnFormHandler.init.apply(returnFormHandler, []);
	}
);

function requestReturnAcceptance()
{
	return false;
}

Event.observe(window, 'load', function(event) {
	if($('banner-port') != null){
		startBanner();

		Event.observe(window, 'mouseout', function(event) {
			event = event ? event : window.event;
			var from = event.relatedTarget || event.toElement;
			if(!from || from.nodeName == "HTML")
			{
				stopBanner();
			}
		});

		Event.observe(window, 'mouseover', function(event) {
			event = event ? event : window.event;
			var from = event.relatedTarget || event.toElement;
			if(!from || from.nodeName == "HTML" || from.nodeName == "BODY")
			{
				startBanner();
			}
		});
	}
	processHash();
});

Event.observe(window, 'load', function(event) {
		var container;
		if ($('container')) {
		container = $('container');
		}
		container.select('.popup').each( function(element) {
		//element.observe('mouseover', Popup.onMouseOver.bindAsEventListener(element));
		element.observe('click', Popup.onClick.bindAsEventListener(element));
	});
});

Event.observe(window, 'load', function() {
	$('cookieoff').hide();
});

// check for a scroll position cookie and set scrollbar to that.
Event.observe(window, 'load', function () {
	var all_cookies = document.cookie.split(";");
	for (i=0; i<all_cookies.length; i++) {
		var all_cookies_pieces = all_cookies[i].split("=");
		if (all_cookies_pieces[0].match("sm_not_back_button")) {
			var d = new Date();
			d.setTime(d.getTime() -1000000);
			if (document.location.toString().indexOf("blank.html") == -1) {
				document.cookie = "sm_not_back_button=1; expires="+d.toGMTString()+";";
			}
			return;
		}
	}

	var url_string = document.location.toString();
	var stripped_url = url_string.replace(/[^A-Za-z0-9]/g, "");
	for (i=0; i<all_cookies.length; i++) {
		all_cookies_pieces = all_cookies[i].split("=");
		if (all_cookies_pieces[0].match(stripped_url)) {
			window.scrollTo(0, all_cookies_pieces[1]);
		}
	}
});
// Set a scroll position cookie so we can scroll to the previous position when they return to this page.
Event.observe(window, 'unload', function() {
	if (document.location.toString().indexOf("blank.html") == -1) {
		var scr = document.viewport.getScrollOffsets();
		var scrY = scr[1];

		var url_string = document.location.toString();
		var stripped_url = url_string.replace(/[^A-Za-z0-9]/g, "");
		var today = new Date();
		var add_time = 1000 * 60 * 20;
		today.setTime(today.getTime() + add_time);
		var exp = today.toGMTString();
		document.cookie = stripped_url+'='+scrY+'; expires='+exp+';';
	}

});
// This sets a cookie when a link is clicked to navigate to another page.
// It is used to differentiate between clicking a link to navigate to another page and clicking the back button to navigate to another page.
Event.observe(window, 'load', function() {
	var all_links = document.getElementsByTagName("a");
	for(i=0; i<all_links.length; i++) {
		if ((all_links[i].id != "next-step-button") && (all_links[i].id != "testimonial_show")) {
			Event.observe(all_links[i], 'click', function () {
				if (document.location.toString().indexOf("blank.html") == -1) {
					document.cookie = "sm_not_back_button=1;";
				}
			});
		}
	}
});

//Event.observe(window, 'load', function(event) {
//	new Draggable("dev-box-container", {handle: 'dev-handle'});
//});
function devLog(message) {
	log = $('dev-box').innerHTML;
	$('dev-box').innerHTML = log + "<br>" + message;
}
function minimizeDev() {
	Effect.SlideUp($('dev-box'));
}
function restoreDev() {
	Effect.SlideDown($('dev-box'));
}
function clearDev() {
	$('dev-box').innerHTML = "";
}
function growDev() {
	new Effect.Scale($('dev-box-container'), 150, {scaleContent: false});
	new Effect.Scale($('dev-box'), 150, {scaleContent: false});
}
function shrinkDev() {
	new Effect.Scale($('dev-box-container'), 50, {scaleContent: false});
	new Effect.Scale($('dev-box'), 50, {scaleContent: false});
}
function showDev() {
	new Effect.Appear($('dev-box-container'), {to: 0.8});
}
function hideDev() {
	new Effect.toggle($('dev-box-container'), 'appear');
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function yesNoConfirm(title, text, onNo, onYes){
	showGraybox('yesNoConfirm',{title: title, text: text, onNo: onNo, onYes: onYes});
}
/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}
var nav_pause = 0;
function showNavDropdown(which_dropdown) {
	clearTimeout(nav_delay);
	hideAllNavDropdown();
	if(pause == 0 && playing == 1){
		pause = 1;
		$('banner_play').removeClassName('pause_btn');
		$('banner_play').addClassName('flashmeplay');
		nav_pause = 1;
	}

	var dropdownobj;
	if (which_dropdown == "manufacturers-dropdown") {
		$("nav-manu").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_brands_hover.jpg') + "')";
		$("nav-manu").style.color = "#333";
		$("manufacturers-dropdown").style.display = "block";
		dropdownobj = $("manufacturers-dropdown");
	} else if (which_dropdown == "categories-dropdown") {
		$("nav-cat").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_categories_hover.jpg') + "')";
		$("nav-cat").style.color = "#333";
		$("categories-dropdown").style.display = "block";
		dropdownobj = $("categories-dropdown");
	} else if (which_dropdown == "licensing-dropdown") {
		$("nav-licensing").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_licensing_hover.jpg') + "')";
		$("nav-licensing").style.color = "#333";
		$("licensing-dropdown").style.display = "block";
		dropdownobj = $("licensing-dropdown");
	}  else if (which_dropdown == "downloads-dropdown") {
		$("nav-downloads").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_licensing_hover.jpg') + "')";
		$("nav-downloads").style.color = "#333";
		$("downloads-dropdown").style.display = "block";
		dropdownobj = $("downloads-dropdown");
	} else {
		hideAllNavDropdown();
	}

	if (navigator.appVersion.indexOf("MSIE 6") != -1) {
		iframeShim(dropdownobj, "nav");
	}
}

var nav_delay;
function showNavDropdownOnDelay(which_dropdown) {
	var nav_elem;
	if (which_dropdown == "manufacturers-dropdown") {
		$("nav-manu").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_brands_hover.jpg') + "')";
		$("nav-manu").style.color = "#333";
	}
	if (which_dropdown == "categories-dropdown") {
		$("nav-cat").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_categories_hover.jpg') + "')";
		$("nav-cat").style.color = "#333";
	}
	if (which_dropdown == "licensing-dropdown") {
		$("nav-licensing").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_licensing_hover.jpg') + "')";
		$("nav-licensing").style.color = "#333";
	}
	nav_delay = setTimeout(function(){showNavDropdown(which_dropdown);}, 500);
	return;
}

function iframeShim(shim_element, which_shim, loc_element, offset_left, offset_top) {
	var shim;
	var shim_pos;
	var shim_zindex = getStyle(shim_element, "zIndex") - 1;

	if (!offset_left) {
		offset_left = 20;
	}
	if (!offset_top) {
		offset_top = 0;
	}

	if (!loc_element) {
		loc_element = shim_element;
	}

	if (which_shim == "popup") {
		shim = $("iframeshimpopup");
		shim_pos = findPos(loc_element);
	}
	if (which_shim == "nav") {
		shim = $("iframeshimnav");
		shim_pos = findPos2(loc_element);
	}

	shim_pos.left += offset_left;
	shim_pos.top += offset_top;

	var shim_height = shim_element.getHeight();
	var shim_width = shim_element.getWidth();
	shim.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
	shim.style.top = shim_pos.top + "px";
	shim.style.left = shim_pos.left + "px";
	shim.style.height = shim_height + "px";
	shim.style.width = shim_width + "px";
	shim.style.zIndex = shim_zindex;
	shim.style.display = "block";
}

function hideAllNavDropdown() {
	clearTimeout(nav_delay);
	$("manufacturers-dropdown").style.display = "none";
	$("categories-dropdown").style.display = "none";
	$("licensing-dropdown").style.display = "none";
	$("downloads-dropdown").style.display = "none";
	$("nav-manu").style.color = "#FFF";
	$("nav-cat").style.color = "#FFF";
	$("nav-licensing").style.color = "#FFF";
	$("nav-downloads").style.color = "#FFF";
	$("nav-manu").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_brands.jpg') + "')";
	$("nav-cat").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_categories.jpg') + "')";
	$("nav-licensing").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_licensing.jpg') + "')";
	$("nav-downloads").style.backgroundImage = "url('" + image_api.get_base_image_url('nav/nav_licensing.jpg') + "')";
	if (nav_pause) {
		pause = 0;
		nav_pause = 0;
		//clearInterval(pauseindicator);
		$('banner_play').removeClassName('flashmeplay');
		$('banner_play').addClassName('pause_btn');
	}

	if ($("iframeshimnav").style.display == "block") {
		$("iframeshimnav").style.display = "none";
	}
}

function setListGrid(e,key,value,id){
	// This is necessary for it to work in IE
	Element.extend(e);

	if(!e.hasClassName('lg_selected')){
		$(e.getAttribute('togglepartner')).removeClassName('lg_selected');
		e.addClassName('lg_selected');
		setFilter(key,value,true,id);
	}
}
function setFilter(key,value,set,id){
	window.scrollTo(0,0);
	var oldHash = location.hash;
	var sep = "&";
	if(oldHash == ""){
		sep = "";
	}
 	if(set){
 		if(key == 'page_on'){
 			if(oldHash.search(/page_on=\d+&/) > 0 && oldHash.search(/&page_on=\d+/) == -1){
 				location.hash = oldHash.replace(/page_on=\d+&/,"");
 			}else if(oldHash.search(/page_on=\d+/) > 0 && oldHash.search(/&page_on=\d+/) == -1){
 				location.hash = oldHash.replace(/page_on=\d+/,"");
 			}else if(oldHash.search(/&page_on=\d+/) > 0){
 				location.hash = oldHash.replace(/&page_on=\d+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key != 'page_on'){
 			if(oldHash.search(/page_on=\d+&/) > 0 && oldHash.search(/&page_on=\d+/) == -1){
 				location.hash = oldHash.replace(/page_on=\d+&/,"");
 			}else if(oldHash.search(/page_on=\d+/) > 0 && oldHash.search(/&page_on=\d+/) == -1){
 				location.hash = oldHash.replace(/page_on=\d+/,"");
 			}else if(oldHash.search(/&page_on=\d+/) > 0){
 				location.hash = oldHash.replace(/&page_on=\d+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key == 'sort_by'){
 			if(oldHash.search(/sort_by=[a-zA-Z_]+&/) > 0 && oldHash.search(/&sort_by=[a-zA-Z_]+/) == -1){
 				location.hash = oldHash.replace(/sort_by=[a-zA-Z_]+&/,"");
 			}else if(oldHash.search(/sort_by=[a-zA-Z_]+/) > 0 && oldHash.search(/&sort_by=[a-zA-Z_]+/) == -1){
 				location.hash = oldHash.replace(/sort_by=[a-zA-Z_]+/,"");
 			}else if(oldHash.search(/&sort_by=[a-zA-Z_]+/) > 0){
 				location.hash = oldHash.replace(/&sort_by=[a-zA-Z_]+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key == 'view_type'){
 			if(oldHash.search(/view_type=[a-zA-Z_]+&/) > 0 && oldHash.search(/&view_type=[a-zA-Z_]+/) == -1){
 				location.hash = oldHash.replace(/view_type=[a-zA-Z_]+&/,"");
 			}else if(oldHash.search(/view_type=[a-zA-Z_]+/) > 0 && oldHash.search(/&view_type=[a-zA-Z_]+/) == -1){
 				location.hash = oldHash.replace(/view_type=[a-zA-Z_]+/,"");
 			}else if(oldHash.search(/&view_type=[a-zA-Z_]+/) > 0){
 				location.hash = oldHash.replace(/&view_type=[a-zA-Z_]+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key == 'search_keywords'){
 			if(oldHash.search(/search_keywords=[a-zA-Z_0-9\s]+&/) > 0 && oldHash.search(/&search_keywords=[a-zA-Z_0-9\s]+/) == -1){
 				location.hash = oldHash.replace(/search_keywords=[a-zA-Z_0-9\s]+&/,"");
 			}else if(oldHash.search(/search_keywords=[a-zA-Z_0-9\s]+/) > 0 && oldHash.search(/&search_keywords=[a-zA-Z_0-9\s]+/) == -1){
 				location.hash = oldHash.replace(/search_keywords=[a-zA-Z_0-9\s]+/,"");
 			}else if(oldHash.search(/&search_keywords=[a-zA-Z_0-9\s]+/) > 0){
 				location.hash = oldHash.replace(/&search_keywords=[a-zA-Z_0-9\s]+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key == 'page_per_view'){
 			if(oldHash.search(/page_per_view=[0-9a-zA-Z]+&/) > 0 && oldHash.search(/&page_per_view=[0-9a-zA-Z]+/) == -1){
 				location.hash = oldHash.replace(/page_per_view=[0-9a-zA-Z]+&/,"");
 			}else if(oldHash.search(/page_per_view=[0-9a-zA-Z]+/) > 0 && oldHash.search(/&page_per_view=[0-9a-zA-Z]+/) == -1){
 				location.hash = oldHash.replace(/page_per_view=[0-9a-zA-Z]+/,"");
 			}else if(oldHash.search(/&page_per_view=[0-9a-zA-Z]+/) > 0){
 				location.hash = oldHash.replace(/&page_per_view=[0-9a-zA-Z]+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		if(key == 'Search Within'){
 			if(oldHash.search(/Search Within=[0-9a-zA-Z]+&/) > 0 && oldHash.search(/&Search Within=[0-9a-zA-Z]+/) == -1){
 				location.hash = oldHash.replace(/Search Within=[0-9a-zA-Z]+&/,"");
 			}else if(oldHash.search(/Search Within=[0-9a-zA-Z]+/) > 0 && oldHash.search(/&Search Within=[0-9a-zA-Z]+/) == -1){
 				location.hash = oldHash.replace(/Search Within=[0-9a-zA-Z]+/,"");
 			}else if(oldHash.search(/&Search Within=[0-9a-zA-Z]+/) > 0){
 				location.hash = oldHash.replace(/&Search Within=[0-9a-zA-Z]+/,"");
 			}
 			oldHash = location.hash;
 			if(oldHash == ""){
 				sep = "";
 			}
 		}
 		location.hash = oldHash+sep+key+"="+value;
	}else{
		if(oldHash.indexOf(key+"="+value+"&") > 0 && oldHash.indexOf("&"+key+"="+value) == -1){
			location.hash = oldHash.replace(key+"="+value+"&","");
		}else if(oldHash.indexOf(key+"="+value) > 0 && oldHash.indexOf("&"+key+"="+value) == -1){
			location.hash = oldHash.replace(key+"="+value,"");
		}else if(oldHash.indexOf("&"+key+"="+value) > 0){
			location.hash = oldHash.replace("&"+key+"="+value,"");
		}
		new Ajax.Updater('filterme', '/ajax/refreshCat/' + id, {
			parameters:{hash:location.hash},
			asynchronous: false,
			onSuccess: function(response) {
				setTimeout(function(){
					Object.values(lpMTagStatic).each(function(i){
					if(typeof i.Start == 'function' && i.buttonName == 'Jeremy Chat Launch'){
        				i.Start();
        			}
					});
				}, 1000);
			}
		});
	}
}

function processHash(){
	if(location.hash != "" && $('cat_id') != null && !$F('cat_id').empty()){
		new Ajax.Updater('filterme','/ajax/refreshCat/' + $F('cat_id'), {
			parameters:{hash:location.hash},
			asynchronous: false,
			onSuccess: function(response) {
				setTimeout(function(){
					Object.values(lpMTagStatic).each(function(i){
					if(typeof i.Start == 'function' && i.buttonName == 'Jeremy Chat Launch'){
        				i.Start();
        			}
					});
				}, 1000);
			}
		});
	}else if(location.hash != ""){
		if(window.location.hash == '#Write-Review'){
		     setTimeout("writeReview()", 100);
		}
		if(window.location.hash == '#Read-Review'){
			setTimeout("readReviews()", 100);
		}
		if(window.location.pathname == "/policies.html"){
			if(window.location.hash.substr(0,3) == "#p="){
				showPolicyDetails(window.location.hash.substr(3));
			}
		}
	}
}
function setSessionReload(key,value,location){
		new Ajax.Request('/ajax/setSessionData/' + key + '/' + value, {
			asynchronous: false
		});
		window.location = location;
}
function changeSortBy(sort_value, id) {
	setFilter("sort_by", sort_value, true, id);
}
function checkForEnter(id,e){
	if(e.keyCode == 13){
		setFilter("Search Within",$F("search_within"),true,id);
	}
}
var hash = location.hash;

setInterval(function(){
	if (location.hash != hash){
		if($('cat_id') != null){
			new Ajax.Updater('filterme', '/ajax/refreshCat/' + $F('cat_id'), {
				parameters:{hash:location.hash},
				asynchronous: false,
				onSuccess: function(response) {
					setTimeout(function(){
						Object.values(lpMTagStatic).each(function(i){
						if(typeof i.Start == 'function' && i.buttonName == 'Jeremy Chat Launch'){
	        				i.Start();
	        			}
						});
					}, 1000);
				}
			});
		}
		if(window.location.hash == '#Write-Review'){
		     setTimeout("writeReview()", 100);
		}
		if(window.location.pathname == "/policies.html"){
			if(window.location.hash.substr(0,3) == "#p="){
				showPolicyDetails(window.location.hash.substr(3));
			}
		}
	        hash = location.hash;
	    }
}, 100);

var playing = 0;
var lastselected = "";
var lastpaused = "";
var delayslide = 0;
var pause = 0;
var pauseindicator = 0;
var oldinnerhtml = "";
var bannerstarter = 0;

function slideBanner(){
	if(lastselected == ""){
		lastselected = $('banner_pos_0');
	}
	if(pause == 0){
		if(delayslide == 0){
			bannerslide = setInterval("slideMe($('banner-holder'),10,680)", 1);
		}else{
			delayslide--;
		}
	}
}
function gotoSlide(e){
	var e = $(e);
	if(lastselected == ""){
		lastselected = $('banner_pos_0');
	}
	if(pause == 0 && playing == 1){
		pause = 1;
		clearInterval(bannerslide);
		$('banner_play').removeClassName('pause_btn');
		//clearInterval(pauseindicator);
//		pauseindicator = setInterval("flashMe($('banner_play'))",500);
		$('banner_play').addClassName('flashmeplay');
	}
	lastselected.removeClassName('flashme');
	e.addClassName('flashme');
	lastselected = $('banner_pos_'+e.getAttribute('slideLoc'));
	$('banner-holder').scrollLeft = e.getAttribute('slideLoc');
}
function flashMe(e){
//	e.toggleClassName('flashmeplay');
}
function forceSlideBanner(n){
	if(lastselected == ""){
		lastselected = $('banner_pos_0');
	}
	if(pause == 0){
		delayslide = 1;
	}
	clearInterval(bannerslide);
	bannerslide = setInterval("slideMe($('banner-holder'),"+n+",680)", 1);
}
function slideMe(e,inc,until){
	var maxloc = $('banner_play').getAttribute('maxLoc');
	if(e.scrollLeft == 0 && inc < 0){
		e.scrollLeft = maxloc;
	}
	e.scrollLeft = e.scrollLeft+inc;
	if(e.scrollLeft %680 == 0){
		clearInterval(bannerslide);
		lastselected.removeClassName('flashme');
		if(e.scrollLeft == maxloc){
			e.scrollLeft = 0;
			if(pause == 0){
				clearInterval(bannerstarter);
				playing = 0;
				$('banner_play').removeClassName('pause_btn');
			}
			$('banner_pos_0').addClassName('flashme');
			lastselected = $('banner_pos_0');
		}else{
			$('banner_pos_'+e.scrollLeft).addClassName('flashme');
			lastselected = $('banner_pos_'+e.scrollLeft);
		}
	}
}
function startBanner(){
	if(playing == 0){
		playing = 1;
		$('banner_play').addClassName('pause_btn');
		bannerstarter = setInterval("slideBanner()",7000);
	}else{
		if(pause == 0){
			pause = 1;
			clearInterval(bannerslide);
			$('banner_play').removeClassName('pause_btn');
			//clearInterval(pauseindicator);
//			pauseindicator = setInterval("flashMe($('banner_play'))",500);
			$('banner_play').addClassName('flashmeplay');
		}else{
			pause = 0;
			//clearInterval(pauseindicator);
			$('banner_play').removeClassName('flashmeplay');
			$('banner_play').addClassName('pause_btn');
		}
	}
}

function stopBanner()
{
	if(playing == 1)
	{
		pause = 1;
		clearInterval(bannerslide);
		$('banner_play').removeClassName('pause_btn');
	}
}
function refresh(){
	window.location.hash = "";
}


function tabHover(tab) {
	document.getElementById(selectedTab+'Tab').className = 'productInfoTabLink';
	document.getElementById(selectedTab+'Box').style.display = 'none';
	document.getElementById(tab+'Tab').className = 'productInfoTabLinkHover';
	document.getElementById(tab+'Box').style.display = '';
	selectedTab = tab;
}

function reviewTabHover(tab,alt) {
	document.getElementById(reviewSelectedTab+'Tab').className = 'productInfoTabLink';
	if(altused != ""){
		document.getElementById(altused+'Box').style.display = 'none';
		altused = "";
	}
	document.getElementById(reviewSelectedTab+'Box').style.display = 'none';
	document.getElementById(tab+'Tab').className = 'productInfoTabLinkHover';
	if(typeof alt != "undefined"){
		document.getElementById(alt+'Box').style.display = '';
		altused = alt;
	}else{
		document.getElementById(tab+'Box').style.display = '';
	}
	reviewSelectedTab = tab;
}

function setZipCookie(zip_code) {
	$('loading_box').style.display = 'block';
	zip_code = validateZipCode(zip_code);

	if (zip_code) {
		document.cookie = "zip_code="+zip_code+"; path=/;";
		window.location.reload();
	} else {
		alert("Please enter a valid zip code")
	}
}

function setZipCookieOnEnter(zip_code, event) {
	var keypressed;
	if (window.event) {
		keypressed = event.keyCode;
	} else if (event.which) {
		keypressed = event.which;
	} else {
		keypressed = "unknown";
	}

	if (keypressed == 13) {
		setZipCookie(zip_code);
		return;
	} else {
		return;
	}
}

function deleteZipCookie() {
	document.cookie = "zip_code=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/;";
	window.location.reload();
}

function setShipMethodCookie(ship_method) {
	document.cookie = "ship_method="+ship_method+"; path=/;";
	window.location.reload();
}

function deleteShipMethodCookie() {
	document.cookie = "ship_method=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/;";
	window.location.reload();
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {left:curleft,top:curtop};
}

function findPos2(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			if ((getStyle(obj, "position") == "relative") || (getStyle(obj, "position") == "absolute")) {
				break;
			}
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return {left:curleft,top:curtop};
}

function getStyle(el, cssprop) {
	if (el.currentStyle) {
		return el.currentStyle[cssprop];
	} else if (document.defaultView && document.defaultView.getComputedStyle) {
		return document.defaultView.getComputedStyle(el, "")[cssprop];
	} else {
		return el.style[cssprop];
	}
}

function showPopupBox(element, popup_text, popup_title, auto_close) {
	var bod = document.getElementsByTagName("body")[0];

	if (document.getElementById("popup_container")) {
		bod.removeChild(document.getElementById("popup_container"));
	}

	var popup_loc = findPos(element);

	var popup_container = document.createElement("div");
	popup_container.id = "popup_container";
	popup_container.style.position = "absolute";
	popup_container.style.zIndex = "1000";
	popup_container.style.left = popup_loc.left + "px";
	popup_container.style.top = popup_loc.top + "px";
	popup_container.style.width = "350px";
	popup_container.style.border = "2px solid #000000";
	popup_container.style.fontSize = "14px";
	popup_container.style.padding = "10px";
	popup_container.style.backgroundColor = "#FFFFDD";

	var top_part = document.createElement("div");
	top_part.style.position = "relative";
	top_part.style.paddingBottom = "5px";

	var sm = document.createElement("span");
	sm.style.fontWeight = "bold";
	sm.style.fontSize = "16px";
	sm.style.textDecoration = "underline";
	if (popup_title) {
		sm.innerHTML = popup_title;
	} else {
		sm.innerHTML = "Softwaremedia.com";
	}

	var close_btn = document.createElement("img");
	close_btn.src = "/application/views/sm/skins/default/images/icons/popup-close-btn.gif";
	close_btn.style.height = "25px";
	close_btn.style.width = "52px";
	close_btn.alt = "Close[X]";
	close_btn.style.position = "absolute";
	close_btn.style.right = "0px";
	close_btn.style.cursor = "pointer";
	close_btn.onclick = function ()
	{
		bod.removeChild(popup_container);
		if ($("iframeshimpopup").style.display == "block") {
			$("iframeshimpopup").style.display = "none";
		}
	}

	if (auto_close == true)
	{
		var rollover_handler = function(e)
		{
			jQuery(this).fadeOut(300);
			jQuery(this).unbind('mouseout', rollover_handler);
			e.stopPropagation();
		}

		jQuery(popup_container).mouseleave(rollover_handler);
	}

	popup_container.appendChild(top_part);
	top_part.appendChild(sm);

	top_part.appendChild(close_btn);

	top_part.style.height = "25px";

	var popup = document.createElement("div");
	popup.innerHTML = popup_text;
	popup_container.appendChild(popup);

	bod.appendChild(popup_container);

	if (navigator.appVersion.indexOf("MSIE 6") != -1) {
		iframeShim($("popup_container"), "popup", element);
	}

}

function getFilterPopupInfo(element, filter_list, table_name, popup_title) {
	var request = new Ajax.Request('/ajax/getFilterPopupInfo', {
		asynchronous: false,
		method: 'post',
		parameters: {filter_list: filter_list, table_name: table_name},
		onComplete: function (transport) {
			showPopupBoxMOver(element, transport.responseText, popup_title);
		}
	});
}


function showPopupBoxMOver(element, popup_text, popup_title, offset_left, offset_top) {
	if (!offset_left) {
		offset_left = 20;
	}
	if (!offset_top) {
		offset_top = 0;
	}
	var bod = document.getElementsByTagName("body")[0];

	if (document.getElementById("popup_container")) {
		bod.removeChild(document.getElementById("popup_container"));
	}

	var popup_loc = findPos(element);
	popup_loc.left += offset_left;
	popup_loc.top += offset_top;

	var popup_container = document.createElement("div");
	popup_container.id = "popup_container";
	popup_container.style.position = "absolute";
	popup_container.style.zIndex = "1000";
	popup_container.style.left = popup_loc.left + "px";
	popup_container.style.top = popup_loc.top + "px";
	popup_container.style.width = "600px";
	popup_container.style.border = "2px solid #000000";
	popup_container.style.fontSize = "14px";
	popup_container.style.padding = "10px";
	popup_container.style.backgroundColor = "#FFFFDD";

	var top_part = document.createElement("div");
	top_part.style.position = "relative";
	top_part.style.paddingBottom = "5px";
	top_part.style.height = "25px";

	var sm = document.createElement("span");
	sm.style.fontWeight = "bold";
	sm.style.fontSize = "16px";
	sm.style.color = "#333";
	sm.style.textDecoration = "underline";
	if (!popup_title) {
		sm.innerHTML = "Softwaremedia.com";
	} else {
		sm.innerHTML = popup_title;
	}

	var close_btn = document.createElement("img");
	close_btn.src = "/application/views/sm/skins/default/images/icons/popup-close-btn.gif";
	close_btn.style.height = "25px";
	close_btn.style.width = "52px";
	close_btn.alt = "Close[X]";
	close_btn.style.position = "absolute";
	close_btn.style.right = "0px";
	close_btn.style.cursor = "pointer";
	close_btn.onclick = function () {
		bod.removeChild(popup_container);
		if ($("iframeshimpopup").style.display == "block") {
			$("iframeshimpopup").style.display = "none";
		}
	}

	popup_container.appendChild(top_part);
	top_part.appendChild(sm);
	top_part.appendChild(close_btn);

	var popup = document.createElement("div");
	popup.innerHTML = popup_text;
	popup_container.appendChild(popup);

	bod.appendChild(popup_container);

	if (navigator.appVersion.indexOf("MSIE 6") != -1) {
		iframeShim($("popup_container"), "popup", element);
	}

}


function removePopupBoxMOut() {
	var bod = document.getElementsByTagName("body")[0];
	if (document.getElementById("popup_container")) {
		bod.removeChild(document.getElementById("popup_container"));
	}
	if ($("iframeshimpopup").style.display == "block") {
		$("iframeshimpopup").style.display = "none";
	}
}

function changeBestsellers(change_to) {
	$("bestsellers_page1").style.display = "none";
	$("bestsellers_page2").style.display = "none";
	$("bestsellers_page3").style.display = "none";

	if (change_to == 1) {
		$("bestsellers_page1").style.display = "block";
	} else if (change_to == 2) {
		$("bestsellers_page2").style.display = "block";
	} else if (change_to == 3) {
		$("bestsellers_page3").style.display = "block";
	} else {
		$("bestsellers_page1").style.display = "block";
	}
}
function dollarPromoPopup(text,e){
	$('dollar-popup').innerHTML = text;
	$('dollar-popup').style.top = (findOffsetTop(e)+e.offsetHeight)+"px";
	$('dollar-popup').style.left = (findOffsetLeft(e)+e.offsetWidth)+"px";
	$('dollar-popup').show();
}
function findOffsetTop(e){
	var top = 0;
	if (e) {
		do {
			top += e.offsetTop;
			e = e.offsetParent;
		}while(e != null);
	}
	return top;
}
function findOffsetLeft(e){
	var left = 0;
	do {
		left += e.offsetLeft;
		e = e.offsetParent;
	}while(e != null);
	return left;
}
function emptyMeChangeTextColor(e,default_phrase,color){
	if(e.value == default_phrase){
		e.value = "";
		e.style.color = color;
	}
}
function checkEmptyReplace(e,default_phrase,color){
	if(e.value == ""){
		e.value = default_phrase;
		e.style.color = color;
	}
}
function refreshManuAll(startwith){
	$('loading_box').style.display = 'block';
	new Ajax.Updater('main', "/ajax/refreshManuAll", {
		asynchronous: false,
		parameters: {startwith:startwith},
		onSuccess: function(trans){
			$('loading_box').style.display = 'none';
		}
	});
}

function refreshLicensingAll(startwith){
	$('loading_box').style.display = 'block';
	new Ajax.Updater('main', "/ajax/refreshLicensingAll", {
		asynchronous: false,
		parameters: {startwith:startwith},
		onSuccess: function(trans){
			$('loading_box').style.display = 'none';
		}
	});
}

function clearNewsLetterInput() {
	if ($("newsletter-signup-email").value == " enter email") {
		$("newsletter-signup-email").value = "";
		$("newsletter-signup-email").style.color = "#333";
	}
}

function repopulateNewsLetterInput() {
	if ($("newsletter-signup-email").value == "") {
		$("newsletter-signup-email").style.color = "#666";
		$("newsletter-signup-email").value = " enter email";
	}
}

function footerNewsLetterSubscribe() {
	var email_address = $("newsletter-signup-email").value;
	if ((email_address == " enter email") || (email_address == "")) {
		showPopupBox($("newsletter-signup-email"), "You must enter your email address to subscribe.")
		return;
	}

	if (!validEmailFormat(email_address)) {
		showPopupBox($("newsletter-signup-email"), "Invalid email address. Please try again.");
		return;
	}

	var request = new Ajax.Request('/ajax/footerNewsLetterSubscribe', {
		asynchronous: false,
		method: 'post',
		parameters: {email_address:email_address},
		onComplete: function (transport) {
			$("newsletter-signup-email").style.color = "#ccc";
			$("newsletter-signup-email").value = " enter email";

			var subscribe_popup_text = "<div style='font-size:18px; font-weight:bold; margin: 10px 0 10px 0;'>Thank you</div>";
			subscribe_popup_text += "<div style='font-weight:bold; margin: 0 0 10px 0;'>Thank you for your interest in SoftwareMedia.com.</div>";
			subscribe_popup_text += "<div style='margin: 0 0 10px 0;'>You have now been subscribed to our mailing list and will be eligible to receive special deals and promotions via email. You may unsubscribe at any time by clicking the unsubscribe link at the bottom of every email.</div>";
			subscribe_popup_text += "<div>Please contact <a style='font-weight:bold;' href='/contact.html'>customer service</a> if you have any questions or concerns.</div>";
			showPopupBox($("newsletter-signup-email"), subscribe_popup_text);
		}
	});
}

function enterForFooterNewsLetterSubscribe(event) {
	var keypressed;
	if (window.event) {
		keypressed = event.keyCode;
	} else if (event.which) {
		keypressed = event.which;
	} else {
		keypressed = "unknown";
	}

	if (keypressed == 13) {
		footerNewsLetterSubscribe();
		return;
	} else {
		return;
	}
}

function validateReviewForm(){
    /*name verification*/
    if($('name').value != ''){
		$('name').removeClassName('reviewFormError');
		$('name_error').style.display = 'none';
    }else{
		$('name').addClassName('reviewFormError');
		$('name_error').style.display = 'block';
    }
    /*email verification*/
    if($('email').value.match(/^[\d\w.-]+?[@]{1}?([\d\w-]+?[.]{1}[\w\d]+?)+?$/)){
		$('email').removeClassName('reviewFormError');
		$('email_error').style.display = 'none';
    }else{
		$('email').addClassName('reviewFormError');
		$('email_error').style.display = 'block';
    }
    if($('short_summary').value.length >= 7 && $('short_summary').value.length <= 35){
		$('short_summary').removeClassName('reviewFormError');
		$('short_summary_error').style.display = 'none';
    }else{
		$('short_summary').addClassName('reviewFormError');
		$('short_summary_error').style.display = 'block';
    }
    /*strengths verification*/
    if($('strengths').value.length >= 1){
		$('strengths').removeClassName('reviewFormError');
		$('strengths_error').style.display = 'none';
    }else{
		$('strengths').addClassName('reviewFormError');
		$('strengths_error').style.display = 'block';
    }
    /*weaknesses verification*/
    if($('weaknesses').value.length >= 1){
		$('weaknesses').removeClassName('reviewFormError');
		$('weaknesses_error').style.display = 'none';
    }else{
		$('weaknesses').addClassName('reviewFormError');
		$('weaknesses_error').style.display = 'block';
    }
    /*rating verification*/
    $('rating-row-container').childElements().each(function(val){
		    if(val.down().checked == true){
				$('selectedRating').value = val.down().value;
		    }
		});
    if($('selectedRating').value > 0){
		$('rating-row-container').removeClassName('reviewFormError');
		$('rating_error').style.display = 'none';
    }else{
		$('rating-row-container').addClassName('reviewFormError');
		$('rating_error').style.display = 'block';
    }
    /*gather all failed elements to decide whether the form is proper or not*/
    var failedElements = jQuery('.reviewFormError');
    if(failedElements.length > 0){
		$('review-form-error').style.display = 'block';
		return false;
    }else{
		$('review-form-error').style.display = 'none';
		return true;
    }
}

function saveReview(){
    if(validateReviewForm()){
		new Ajax.Request('/ajax/saveReview/test',{
		    asynchronous: false,
		    parameters: {
				name: $('name').value,
				email: $('email').value,
				city: $('city').value,
				state: $('state').value,
				product: $('product_id').value,
				short_summary: $('short_summary').value,
				strengths: $('strengths').value,
				weaknesses: $('weaknesses').value,
				general_comments: $('general_comments').value,
				rating: $('selectedRating').value,
				newsletter: $('newsletter').checked
		    },
		    onSuccess: function(transport){
				if(transport.responseText == 'true'){
				    $('writeReviewBox').innerHTML = "<div class='panel-wrapper'>Your review has been submitted. If approved, it will appear on the site within 48 business hours. Thank you.</div>";
				}else{
				    $('writeReviewBox').innerHTML = "<div class='panel-wrapper'>There was a problem submitting your review, please call Customer Service, Toll Free @ 1-800-474-1045, so that we can troubleshoot your error.<br><br>Thank you,<br>The Development Team</div>";
				}
		    }
		});
    }
}

function readReviews(){
	reviewTabHover("review");
	window.scrollTo(0,findOffsetTop($('write-review')));
}

function writeReview(){
	reviewTabHover("review","writeReview");
    window.scrollTo(0,findOffsetTop($('write-review')));

}

function countText(source, target, max_length){
    var length = source.value.length;
    $(target).innerHTML = max_length - length;
}

function getPopupTextFromDB(element, popup_name, popup_type) {
	var request = new Ajax.Request('/ajax/getPopupText', {
		asynchronous: false,
		method: 'post',
		parameters: {popup_name: popup_name, popup_type: popup_type},
		onComplete: function (transport) {
			showPopupBox(element, transport.responseText, popup_type);
		}
	});
}

function getSpecificationPopup(element, item_id, popup_type, popup_name) {
	var request = new Ajax.Request('/ajax/getSpecificationPopup', {
		asynchronous: false,
		method: 'post',
		parameters: {item_id: item_id, popup_type: popup_type},
		onComplete: function (transport) {
			showPopupBox(element, transport.responseText, popup_name);
		}
	});

}

function getStockDescriptionPopup(element, stock_description_id) {
	var request = new Ajax.Request('/ajax/getStockDescriptionPopup', {
		asynchronous: false,
		method: 'post',
		parameters: {stock_description_id: stock_description_id},
		onComplete: function (transport) {
			showPopupBox(element, transport.responseText);
		}
	});

}
function showMore(element){
	if (element.style.display == "none") {
		element.style.display = "block";
		element.style.overflow = "hidden";
		var height = element.offsetHeight;
		var movement = 5;
		element.style.height = "0px";
		var slider = setInterval(function(){
			if(element.offsetHeight < height){
				element.style.height = (element.offsetHeight+movement)+"px";
			}else{
				element.style.height = height+"px";
				clearInterval(slider);
			}
		},10);
	} else {
		element.style.overflow = "hidden";
		var movement = 5;
		var slider = setInterval(function(){
			if(element.offsetHeight-movement > 0){
				element.style.height = (element.offsetHeight-movement)+"px";
			}else{
				element.style.height = "auto";
				element.style.display = "none";
				clearInterval(slider);
			}
		},10);
	}
}

function validEmailFormat(email) {
	if (email.match(/^[\d\w.-]+?[@]{1}?([\d\w-]+?[.]{1}[\w\d]+?)+?$/)) {
		return true;
	} else {
		return false;
	}
}
function continueToBeta(){
	setSessionReload("beta_agree",1,"");
	closeGraybox();
	startBanner();
}
function applyDisorNot(ele,target){
	if(!ele.value.empty()){
		if(!target.hasClassName('apply-grey')){
			target.removeClassName('apply-grey-disabled');
			target.addClassName('apply-grey');
		}
	}else{
		if(!target.hasClassName('apply-grey-disabled')){
			target.removeClassName('apply-grey');
			target.addClassName('apply-grey-disabled');
		}
	}
}

function submitPasswordReset() {
	var new_password = $("new_password").value.strip();
	var repeat_password = $("repeat_password").value.strip();
	if (!new_password) {
		showPopupBox($("reset_submit_btn"), "Please enter a password");
		return;
	}

	if (new_password.length < 8) {
		showPopupBox($("reset_submit_btn"), "Your password must be at least 8 characters");
		return;
	}

	if (new_password == repeat_password) {
		var user_id = $("user_id").value;
		var request = new Ajax.Request('/ajax/resetPassword', {
			asynchronous: false,
			method: 'post',
			parameters: {user_id: user_id, password: new_password},
			onComplete: function (transport) {
				showPopupBox($("reset_submit_btn"), "Your password has been set. Click <a href='/account/'>here</a> to log in.");
			}
		});
	} else {
		showPopupBox($("reset_submit_btn"), "Passwords do not match");
	}
	return;
}

function enterForFunction(event, func) {
	var keypressed;
	if (window.event) {
		keypressed = event.keyCode;
	} else if (event.which) {
		keypressed = event.which;
	} else {
		keypressed = "unknown";
	}

	if (keypressed == 13) {
		func();
	} else {
		return false;
	}
}

function quickLinksTracking(event, category_id, click_type, identifier) {
	var elem = event.target != null ? event.target : event.srcElement;
	if (!identifier) {
		var identifier = "unknown";
		if (elem.tagName == "IMG") {
			if (elem.alt != "") {
				identifier = elem.alt;
			} else {
				identifier = elem.src;
			}
		}
	}
	var request = new Ajax.Request('/ajax/quickLinksTracking', {
		asynchronous: false,
		method: 'post',
		parameters: {identifier: identifier, category_id: category_id, click_type: click_type}
	});
}

function hideHint(){
	$('filter_hint').hide();
	session = new Session;
	session._SetSessionData("hide_hint",1);
}

/* For counting checkboxes for product comparisons */
function countBoxes(id) {
	var checkedBoxes = new Array();
	var uncheckedBoxes = new Array();
	var boxes = jQuery('.compare-check-boxes');
	var boxDivs = jQuery('.compare-box');
	jQuery(boxes).each(function() {
		if (jQuery(this).attr('checked') == true){
			checkedBoxes.push(jQuery(this));
		}
		else uncheckedBoxes.push(jQuery(this));
	});
	if (jQuery(checkedBoxes).size() >= 2){
		jQuery('#compare_button').attr("src", image_api.get_base_image_url("buttons/compare-btn.jpg"));
		if (id == 'compare_button'){
			document.compareForm.submit();
		}
	}
	else if (jQuery(checkedBoxes).size() < 2) {
		jQuery('#compare_button').attr("src", image_api.get_base_image_url("buttons/compare-btn-grey.jpg"));
	}

	if (jQuery(checkedBoxes).size() == 5) {
		jQuery(uncheckedBoxes).each(function(){
			jQuery(this).attr('disabled', true);
			if(this.next('span') != null){
				jQuery(this.next('span')).addClass('disable-check-box');
			}
		});
	}
	else {
		jQuery(uncheckedBoxes).each(function(){
			jQuery(this).attr('disabled', false);
			if(this.next('span') != null){
				jQuery(this.next('span')).removeClass('disable-check-box');
			}
		});
	}
}

// For removing columns from the compare page
function destroyComp(name, count, compId) {
	if(count == 2){
		history.go(-1);
	}
	else {
		// Remove product
		var toRemove = name.substring(0,8);
		jQuery('.'+toRemove).remove();
		jQuery('#comp_count').val(--count);
		percentage = Math.round(jQuery('#comp_count').value * 100);
		jQuery("td").attr({
			style: "width:"+(percentage)+"%"
		});

		// Remove ID for sharing purposes
		ids = jQuery('#comp_share').val();
		available_ids = ids.split(",");
		ids_holder = new Array();
		for (i=0;i<available_ids.length;i++){
			if (available_ids[i] != compId && available_ids[i] != ""){
				ids_holder.push(available_ids[i]);
			}
		}
		new_ids = ids_holder.join();
		jQuery('#comp_share').val(new_ids);
	}
}

function shareComparison(evt, IEisGay, IEisAHomo, IEisALez, IEisAQueer){
	ids = jQuery('#comp_share').val().split(",");
	if (ids[ids.length-1] == "")
		ids.pop();
	pass = ids.join();

	jQuery.ajax({
		url: '/compare/createShareLink',
		type:	'POST',
		data:	"id_vals="+pass,
		success:	function(data) {
			jQuery('#share_link_input').val(data);
			jQuery('#share_link_input').focus(
				function() {
					this.select(); // In an effort to help with this stupid feature I have made the text selection automatic so users will only have to push ctrl+c
				}
			).keyup(function(){
				if (jQuery('#share_link_input') != data)
					jQuery('#share_link_input').val(data);
			});
			$('share_link').style.display = "block";
			if(evt.pageX == null){
				// IE is so gay that I was forced to pass the event.[clientX,clientY,document.documentElement.scrollLeft(scrollTop)] values straight to the function.
				// For some reason if you try and used a passed event object, IE strips all the values contained inside of it.
				$('share_link').style.left = ((IEisGay+IEisAQueer) - $('share_link').offsetWidth)+'px';
				$('share_link').style.top = ((IEisAHomo+IEisALez) + 10)+'px';
			}
			else {
				$('share_link').style.left = (evt.pageX - $('share_link').offsetWidth)+'px';
				$('share_link').style.top = (evt.pageY + 10)+'px';
			}
		}
	})
}

function launchTryItFree(e){
	var popup_loc = findPos(e);

	$('tryitfree-popup').show();
	$('tryitfree-popup').style.left = (popup_loc.left - ($('tryitfree-popup').offsetWidth/2))+ "px";
	$('tryitfree-popup').style.top = (popup_loc.top - ($('tryitfree-popup').offsetHeight/2)) + "px";
}
function tryItSignUp(name,comp,email,item_id,tifid){
	if(!name.empty() && !email.empty()){
		new Ajax.Request('/ajax/tryItFree',
			{
				asynchronous: false,
				parameters: { name: name, email: email, comp:comp,item_id:item_id,tifid:tifid},
				onSuccess: function(t){
					window.open(t.responseText,'tiflink');
					$('tryitfree-popup').hide();
					$('tif_error').hide();
				}
			});
	}else{
		var tmp = "";
		var c = "";
		if(name.empty()){
			tmp = " Name";
		}
		if(email.empty()){
			if(!tmp.empty()){
				c = ",";
			}
			tmp += " "+c+"Email";
		}
		$('tif_error').innerHTML = "Please Enter the Following Fields: "+tmp;
		$('tif_error').show();
	}
}
function closeShareLink(){
	jQuery('#share_link').hide();
}
function showTIFFAQ(e){
	e.next().show();
	e.next().next().show();
	e.style.textDecoration = "none";
	e.style.fontWeight = "bold";
	e.style.color = "#000";
}

function hideTIFFAQ(e){
	e.next().hide();
	e.hide();
	e.previous().style.textDecoration = "underline";
	e.previous().style.fontWeight = "none";
	e.previous().style.color = "#335E96";
}

/**
 * A helper function for the safeOnMouseOut and safeOnMouseTransition functions
 * @param parent
 * @param child
 * @return
 */
function is_child_of(parent, child) {
	if( child != null ) {
		while( child.parentNode ) {
			if( (child = child.parentNode) == parent ) {
				return true;
			}
		}
	}
	return false;
}

/**
 * Use this to cause a safe mouse out to happen. This function will check to make sure that the mouse out only
 * occurs when the mouse is moving out of the parent element and will not fire when called from a child of the parent element
 * @param element (this)
 * @param event
 * @param JS_function (String) - This is the function to be called, if element is not a child of the parent element.
 * @return null
 */
function safeOnMouseOut(element, event, JS_function, js_params) {
	var current_mouse_target = null;
	if( event.toElement ) {
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {
		current_mouse_target 			 = event.relatedTarget;
	}
	if(typeof js_params == 'undefinded') {
		js_params = {};
	}
	if( !is_child_of(element, current_mouse_target) && element != current_mouse_target ) {
		this[JS_function](js_params);
	}
}

/**
 * Use this to keep a mouse out event from occuring when the mouse transitions elements, and a mouse out event is not desired
 * @param target_element (String)
 * @param event
 * @param JS_function
 * @return
 */
function safeOnMouseTransition(target_element, event, JS_function){
	var current_mouse_target = null;
	if( event.toElement ) {
		current_mouse_target 			 = event.toElement;
	} else if( event.relatedTarget ) {
		current_mouse_target 			 = event.relatedTarget;
	}

	if(current_mouse_target != target_element){
		this[JS_function]();

	}
}

/**
 * Functions for the Review Products page found under My Account
 */
jQuery(document).ready(function($){
	$('.review-product-row').bind('mouseover mouseout', changeColor);
	$('.review-product-image').bind('click', goToReview);
});

function changeColor(e){
	if(jQuery(this).css('background-color') == 'transparent'){
		jQuery(this).css('background-color', '#E4E4E4');
	} else {
		jQuery(this).css('background-color', 'transparent');
	}
}

function goToReview(){
//	console.log(window.location.hostname);
	window.location = 'http://'+window.location.hostname+''+jQuery(this).next().attr('href');
}

// ------------ End Review Products functions

