
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('/home/eraseCookie',{ asynchronous: false, parameters: { cookie_name: i.key, cookie_email: i.value}});
	});
	window.location = "";
}

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 sameAsBillingAddress() {
	if ($("same_as_billing").checked == true) {
		$("shipping_name").value 		= $("billing_name").value;
		$("shipping_company").value 	= $("billing_company").value;
		$("shipping_address1").value 	= $("billing_address1").value;
		$("shipping_address2").value 	= $("billing_address2").value;
		$("shipping_city").value 		= $("billing_city").value;
		$("shipping_state").value 		= $("billing_state").value;
		$("shipping_zip").value 		= $("billing_zip").value;
		$("shipping_phone").value 		= $("billing_phone").value;
	} 
}

function blankOutShippingInfo() {
	if ($("same_as_billing").checked == true) {
		$("shipping_name").readOnly 	= true;
		$("shipping_company").readOnly 	= true;
		$("shipping_address1").readOnly = true;
		$("shipping_address2").readOnly = true;
		$("shipping_city").readOnly 	= true;
		$("shipping_state").readOnly 	= true;
		$("shipping_zip").readOnly 		= true;
		$("shipping_phone").readOnly 	= true;
	
	} else {
		$("shipping_name").value 		= "";
		$("shipping_company").value 	= "";
		$("shipping_address1").value 	= "";
		$("shipping_address2").value 	= "";
		$("shipping_city").value 		= "";
		$("shipping_state").value 		= "";
		$("shipping_zip").value 		= "";
		$("shipping_phone").value 		= "";
		
		$("shipping_name").readOnly 	= false;
		$("shipping_company").readOnly 	= false;
		$("shipping_address1").readOnly = false;
		$("shipping_address2").readOnly = false;
		$("shipping_city").readOnly 	= false;
		$("shipping_state").readOnly 	= false;
		$("shipping_zip").readOnly 		= false;
		$("shipping_phone").readOnly 	= false;
	}
}

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 = "Your SoftwareMedia.com account password has been emailed 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){
	if(num != "" && num != null && cvv != "" && cvv != null){
		new Ajax.Updater('balance', '/account/getGiftCardBalance/' + num + '/' + cvv, {
			asynchronous: false
		});
	}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, 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('/product/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 = "";
}
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.";
		document.fire('cart:' +response.event,response.parameters);		
		showGraybox('message', {message_title: 'Cart Saved', message: message});
	} else {
		showGraybox('cart/email',{});
		closeGraybox({event: 'save_cart',  parameters: {email: $F('email')}});
	}
}

function enableReturn() {
	if ($('accept').checked == true) {
		$('airBill').disabled = false;
		$('shipSelf').disabled = false;
	} else {
		$('airBill').disabled = true;
		$('shipSelf').disabled = true;
	}
}


Event.observe(window, 'load', function(event) {
	var container;
	if (!$('center-col')) {
		container = $('checkout-center-col');
	} else {
		container = $('center-col');
	}
	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() {
	if(readCookie("cookieson") == null){
		$('cookieoff').show();
	}
	/*
	 * Get all the menu elements and alter their CSS appropriately.
	 * Then attach the onclick function to the <h2> tag.
	 */
	session = new Session;
	session._GetSessionData("selected_menu");
	var selected_menu = session._responseText
	$('view-cart-items').hide();
	$('view-cart-items').style.visibility = "visible";
	if ($('right-container')) {
		var elements = $('right-container').childElements();
		elements.each(
			function(value){
				var catElements = value.childElements();
				
				catElements.each(
					function(value2) { 
						if (value2.tagName == "H2") {
							if (value2.id == selected_menu) {
								nextObject(value2).show();
								//nextObject(value2).style.display = 'block';
							} else {
								nextObject(value2).style.display = 'none';
								nextObject(value2).hide();
							}
							nextObject(value2).style.visibility = 'visible';
							nextObject(value2).style.height = 'auto';
							if(value2.id != "menu-downloads"){
								value2.onclick = function() {menuSlide(value2);}
							}
						}
					}
				);
				
			}
		)
	}
});

// check for a scroll position cookie and set scrollbar to that.
Event.observe(window, 'load', function () {
	all_cookies = document.cookie.split(";");

	for (i=0; i<all_cookies.length; i++) {
		all_cookies_pieces = all_cookies[i].split("=");
		if (all_cookies_pieces[0].match("sm_not_back_button")) {
			d = new Date();
			d.setTime(d.getTime() -1000000);
			document.cookie = "sm_not_back_button=1; expires="+d.toGMTString()+";";
			return;
		} 
	}
	
	url_string = document.location.toString();
	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() {
	scr = document.viewport.getScrollOffsets();
	scrY = scr[1];
	
	url_string = document.location.toString();
	stripped_url = url_string.replace(/[^A-Za-z0-9]/g, "");
	today = new Date();
	add_time = 1000 * 60 * 20;
	today.setTime(today.getTime() + add_time);
	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() {
	all_links = Element.select('a');
//	all_links = document.getElementsByTagName("a");
	all_links.each(function(value){
		if ((value.id != "next-step-button") && (value.id != "testimonial_show")) {
			Event.observe(value, 'click', function () {document.cookie = "sm_not_back_button=1;";});
		}
	});
//	for(i=0; i<all_links.length; i++) {
//		if ((all_links[i].id != "next-step-button") && (all_links[i].id != "testimonial_show")) {
//			//all_links[i].onclick = function () {
//			//	document.cookie = "sm_not_back_button=1;";
//			//}
//			Event.observe(all_links[i], 'click', function () {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});
}
