﻿function getQueryParam(variable) 
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) 
    {
        var pair = vars[i].split("=");
        if (pair[0] == variable) 
        {
            return pair[1];
        }
    }
    return "movie";  // default
}

function search(form) 
{    
	var searchTerm = form.searchField.value;	
	if (searchTerm.replace(/\s/g, "") == "")
		return false;

    var queryString = "term=" + escape(searchTerm);
	
	if (form.searchType.value == "Digital Movies")
		queryString += "&tab=movie";
	else if (form.searchType.value == "Digital TV")
		queryString += "&tab=tv";
	else if (form.searchType.value == "DVDs")
		queryString += "&tab=dvd";
	else if (form.searchType.value == "All Digital")
		queryString += "&tab=alldigital";   				
	else 
        queryString += "&tab=" + getQueryParam("tab");
        
	document.location.href = basePath + 'search?' + queryString;
}

function UpdateCheckoutNewCard(newCardRadio, editNewCardDiv) 
{
	document.getElementById(editNewCardDiv).style.display = document.getElementById(newCardRadio).checked ? "block" : "none";
}

function IsValidEmailAddress(emailAddress) 
{
     var emailReg=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
     var regex = new RegExp(emailReg);
     return regex.test(emailAddress);
}

function IsValidPassword(password)
{
    var passwordReg = /^[0-9A-Za-z]{1}[\d|\w|!|@|#|$|%|^|*]{5,23}$/; 
    var regex = new RegExp(passwordReg);
    return regex.test(password);
}

function IsCreditCardValid( cardNumber ) 
{ 
    var clen = new Array( cardNumber.length ); 
    var n = 0,sum = 0; 
    for( n = 0; n < cardNumber.length; ++n ) 
    { 
        clen [n] = parseInt( cardNumber.charAt(n) ); 
    } 
    for( n = clen.length -2; n >= 0; n-=2 ) 
        clen [n] *= 2; 
    if( clen [n] > 9 ) 
        clen [n]-=9;
    for( n = 0; n < clen.length; ++n ) 
        sum += clen [n]; 
    return(((sum%10)==0)?true : false);
} 

function Print(object)
{ 
    var disp_setting="toolbar=no,location=yes,directories=yes,menubar=yes,";
        disp_setting+="scrollbars=yes,width=750,height=650,left=10,top=10";
    
    var content_value = $(object);    
    var docprint = window.open("", "", disp_setting);
    docprint.document.open();
    docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');     
    docprint.document.write('<html><head><title>Purchase Record</title>');
    docprint.document.write('<link rel="stylesheet" type="text/css" href="'+ basePath +'stylesheets/' + site + '/color.css" />');
    docprint.document.write('<link rel="stylesheet" type="text/css" href="'+ basePath +'stylesheets/' + site + '/type.css" />');
    docprint.document.write('<link rel="stylesheet" type="text/css" href="'+ basePath +'stylesheets/' + site + '/screen.css" />');
    docprint.document.write('<link rel="stylesheet" type="text/css" href="'+ basePath +'stylesheets/' + site + '/print.css" />');
    docprint.document.write('</head><body onload="self.print(); self.close();" >');
    docprint.document.write('<h1>Road Runner Video Store</h1>');
    docprint.document.write(content_value.innerHTML);
    docprint.document.write('</body></html>');
    docprint.document.close();
    docprint.focus();    
    return false;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

var mouseOverDropdownTimeout;

var Rules = {
	'.submit_button:click': function(element, e) {
		if (element.disabled) {
			Event.stop(e);
			return false;
		}

		RefreshDisabledOverlays();

		var validation_group = element.classNames().find(function(cn) { return cn.startsWith('validation_group_'); });

		if (typeof (Page_ClientValidate) == 'function') {
			if (validation_group) {
				validation_group = validation_group.substr('validation_group_'.length);

				if (validation_group != "none" && !Page_ClientValidate(validation_group)) {
					return false;
				}
			}
			else if (!Page_ClientValidate(validation_group)) {
				return false;
			}
		}

		$$(".submit_button").each(function(b) {
			Element.disable(b);
		});
	},

	'div.fancy_cbo:mouseout': function(element, e) {
		mouseOverDropdownTimeout = setTimeout(function() {
			Element.findParentByClass(element, "fancy_cbo").down().next().style.visibility = "hidden";
		}, 200);
	},

	'div.fancy_cbo:mouseover': function(element, e) {
		clearTimeout(mouseOverDropdownTimeout);
	},

	'a.default_button': function(element, e) {
		element.click = function() {
			var result = true;
			if (element.onclick) result = element.onclick();
			if (typeof (result) == 'undefined' || result) {
				eval(unescape(element.href));
			}
		}
	},

	'input.default_focus': function(element, e) {
		if (!(element.disabled == true || element.style.visibility == 'hidden' || element.style.display == 'none'))
			setTimeout(function() { try { element.focus(); } catch (err) { } }, 1);
	},

	'a.shopping_cart_add_button:click': function(element, e) {
		try {
			s_helper.TrackAddtoCart(Element.findParentByClass(element, "shopping_cart_add_button"));
		} catch (err) { }
	},

	'span.new_address_radio input:click, span.address_list input:click': function(element, e) {
		$$("span.new_address_radio input[type='radio'], span.address_list input[type='radio']").each(
			function(i) {
				if (i != element)
					i.checked = false;
			});

		SetSelectedAddress(element);
	},

	'a#dvd_add_shopping_cart:click': function(element, e) {
		Event.stop(e);

		if (!$F('dvd_other_quantity').match(/^\d+$/) || $F('dvd_other_quantity') == '0' || $F('dvd_other_quantity') == '00') {
			$('validation_errors').show();
			$('dvd_other_quantity').style.border = "2px solid red";
			$('dvd_other_quantity').focus();
			$('dvd_other_quantity').select();
			return;
		}
		$('validation_errors').hide();
		var quantity = parseInt($F('dvd_other_quantity'));

		document.location.href = $('dvd_add_shopping_cart').href + "&quantity=" + quantity;
	},

	'select#dvd_select_quantity:change': function(element, e) {
		if ($F(element) == 'other') {
			element.hide();
			$('dvd_other_quantity').show();
			$('dvd_other_quantity').focus();
			$('dvd_other_quantity').select();
		}
	},

	'a#tv_networks:mouseout': function(element, e) {
		mouseOverSubnavTimeout = setTimeout(function() {
			$('sub_tv_networks').hide();
			$('tv_networks').removeClassName('active');
		}, 100);

	},

	'a#tv_networks:mouseover': function(element, e) {
		$('sub_tv_networks').show();
		$('tv_networks').addClassName('active');
	},

	'a#tv_genres:mouseout': function(element, e) {
		mouseOverSubnavTimeout = setTimeout(function() {
			$('sub_tv_genres').hide();
			$('tv_genres').removeClassName('active');
		}, 100);

	},

	'a#tv_genres:mouseover': function(element, e) {
		$('sub_tv_genres').show();
		$('tv_genres').addClassName('active');
	},

	'a#movie_genres:mouseout': function(element, e) {
		mouseOverSubnavTimeout = setTimeout(function() {
			$('sub_movie_genres').hide();
			$('movie_genres').removeClassName('active');
		}, 100);

	},

	'a#movie_genres:mouseover': function(element, e) {
		$('sub_movie_genres').show();
		$('movie_genres').addClassName('active');
	},

	'a#movie_studios:mouseout': function(element, e) {
		mouseOverSubnavTimeout = setTimeout(function() {
			$('sub_movie_studios').hide();
			$('movie_studios').removeClassName('active');
		}, 100);

	},

	'a#movie_studios:mouseover': function(element, e) {
		$('sub_movie_studios').show();
		$('movie_studios').addClassName('active');
	},

	'div.subnav:mouseout': function(element, e) {

		mouseOverSubnavTimeout = setTimeout(function() {
			var items = $$('div.subnav');
			for (i = 0; i < items.length; i++) {
				$(items[i]).hide();
			}
			i = 0;
			items = $$('a.subnav');
			for (i = 0; i < items.length; i++) {
				$(items[i]).removeClassName('active');
			}
		}, 100);
	},

	'div.subnav:mouseover': function(element, e) {
		clearTimeout(mouseOverSubnavTimeout);
		//alert("test");
		//$('sub_tv_networks').show();
	},

	'a.disabled': function(element) {
		Element.disable(element);
	},

	'td.quantity input:keyup': function(element) {
		$$('a.update_button.disabled').each(function(e) {
			Element.enable(e);
		});
	},
	'.row a.theaction:click': function(element, e) {
		var expandable = Element.findParentByClass(element, "row");
		Expandable.toggle(expandable);		
		
		Event.stop(e);
	},
	'.row_alt a.theaction:click': function(element, e) {
		var expandable = Element.findParentByClass(element, "row_alt");
		Expandable.toggle(expandable);		
		
		Event.stop(e);
	},
	'div.expanding a.theaction:click': function(element, e) {
		var expandable = Element.findParentByClass(element, "expanding");
		Expandable.toggle(expandable);
	},
	'div.input_box input:focus': function(element, e) {
	    SearchBar.focused(element);
	},
	'div.cboMainButton:mouseover': function(element, e) {
	    element.style.cursor = 'pointer';
	}
};

var Expandable = {
	toggle: function(expandableElement) {
		if (expandableElement.hasClassName("expanded"))
			this.collapse(expandableElement);
		else
			this.expand(expandableElement);
	},
	
	collapse: function(expandableElement) {
		expandableElement.removeClassName("expanded");
		expandableElement.addClassName("collapsed");
	},
	
	expand: function(expandableElement) {
		expandableElement.removeClassName("collapsed");
		expandableElement.addClassName("expanded");
	}
}

var SearchBar = {
	_hasFocused: new Hash(),
	
	focused: function(element) {	
		if (!this._hasFocused[element.up().id])
		{
			this._hasFocused[element.up().id] = true;
			element.value = '';
		}
	}
}
function sleep(millisecond_delay) {
	if (window.sleep_delay != undefined) clearTimeout(window.sleep_delay);
	var function_object = this;
	window.sleep_delay = setTimeout(function_object, millisecond_delay);
};

EventSelectors.register(Rules);

Event.observe(window, "load", function() {
    /*
	if ($('leftBannerSnippetLocation') && $('ads'))
	{
		new Ajax.Request($F('leftBannerSnippetLocation'), {
		  method: 'GET',
		  crossSite: true
		});
	}
    */
	$$('div.address_container').each(function (element) {
		element.style.height = (element.up().getHeight() - 10) + 'px';
				
		element.select('div.address_edit_controls').each(function(e) {
			e.style.position = 'absolute';
			e.style.bottom = '0px';
		});
	});
	
	$$('div.shipping_address_container').each(function (element) {
		element.style.height = (element.up().getHeight() - 20) + 'px';
				
		element.select('div.address_edit_controls').each(function(e) {
			e.style.position = 'absolute';
			e.style.bottom = '0px';
		});
	});
	
		$$('div.billing_address_container').each(function (element) {
		element.style.height = (element.up().getHeight() - 20) + 'px';
				
		element.select('div.address_edit_controls').each(function(e) {
			e.style.position = 'absolute';
			e.style.bottom = '0px';
		});
	});
}, false);

Event.observe(window, "resize", function() {
  RefreshDisabledOverlays();
}, false);

Element.findParentByClass = function(element, className) {
	if (element.hasClassName(className))
		return element;
	return Element.ancestors(element).find(function(elem) { return elem.hasClassName(className) });
}

Element.focusFirstTextbox = function(element) {
	element = $(element);
	var textBoxes = element.select("./input[@type='text']");

	if (textBoxes.length > 0)
		textBoxes[0].focus();
}

var _disabledOverlays = new Map();

Element.disable = function(element) {
		if (Element.isDisabled(element))
			return;
			
		var overlay = $('overlays').insert({top: "<div class='disabled_overlay'></div>"}).down();
		overlay.clonePosition($(element));

		_disabledOverlays.put($(element), overlay);
		
		$(element).addClassName('has_overlay');
}

Element.enable = function(element) {
	if (!Element.isDisabled(element))
		return;
		
	_disabledOverlays.get($(element)).hide();
	_disabledOverlays.remove($(element));
	
	$(element).removeClassName('has_overlay');
}

Element.isDisabled = function(element) {
	return _disabledOverlays.get($(element)) != null && typeof(_disabledOverlays.get($(element))) != 'undefined';
}

function RefreshDisabledOverlays() {
	setTimeout(function() {
		$$('.has_overlay').each(function(e) {
			if (Element.isDisabled(e))
				_disabledOverlays.get(e).clonePosition(e);
		});
	}, 0);
}

function SetSelectedAddress(element)
{
	if (element == NewAddress.NewAddressRadio)
	{
		Element.enable('newAddressFields');
		//$$('#newAddressFields input, #newAddressFields select').each(function(i) { i.disabled = false; });
		
		NewAddress.SelectedAddressID.value = "";
		NewAddress.NewAddressRadio.checked = true;
		NewAddress.Name.focus();
	}
	else
	{ 
		if (!Element.isDisabled('newAddressFields'))
			Element.disable('newAddressFields');
		//$$('#newAddressFields input, #newAddressFields select').each(function(i) { i.disabled = true; });
		
		NewAddress.NewAddressRadio.checked = false;
			
		NewAddress.Name.value = element.address.Name;
		NewAddress.AddressLine1.value = element.address.AddressLine1;
		NewAddress.AddressLine2.value = element.address.AddressLine2;
		NewAddress.City.value = element.address.City;
		NewAddress.State.value = element.address.State;
		NewAddress.Zip.value = element.address.Zip;
		NewAddress.Country.value = element.address.CountryCode;
		
		NewAddress.PhoneNumber.value = "(" + element.address.PhoneNumber1 + ") " +
		                               element.address.PhoneNumber2 + "-" + 
		                               element.address.PhoneNumber3;
		                                
		NewAddress.SelectedAddressID.value = element.address.ID;
	}
}

// linking the key-value-pairs is optional
// if no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
    this.current = undefined;
    this.size = 0;

    if(linkItems === false)
        this.disableLinking();
}

Map.noop = function() {
    return this;
};

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");
};

// map initialisation from existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;

    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);
    }

    return map;
};

Map.prototype.disableLinking = function() {
    this.link = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop;
    this.next = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
    this.removeAll = Map.illegal;

    return this;
};

// overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
   if (value == null)
	return null;
	 
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :
        value.toString());
};

Map.prototype.hash.current = 0;

// --- mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    return item === undefined ? undefined : item.value;
};

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;

        this.link(item);
        ++this.size;
    }
    else this[hash].value = value;

    return this;
};

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];

    if(item !== undefined) {
        --this.size;
        this.unlink(item);

        delete this[hash];
    }

    return this;
};

// only works if linked
Map.prototype.removeAll = function() {
    while(this.size)
        this.remove(this.key());

    return this;
};

// --- linked list helper functions

Map.prototype.link = function(item) {
    if(this.size == 0) {
        item.prev = item;
        item.next = item;
        this.current = item;
    }
    else {
        item.prev = this.current.prev;
        item.prev.next = item;
        item.next = this.current;
        this.current.prev = item;
    }
};

Map.prototype.unlink = function(item) {
    if(this.size == 0)
        this.current = undefined;
    else {
        item.prev.next = item.next;
        item.next.prev = item.prev;
        if(item === this.current)
            this.current = item.next;
    }
};

// --- iterator functions - only work if map is linked

Map.prototype.next = function() {
    this.current = this.current.next;
};

Map.prototype.key = function() {
    return this.current.key;
};

Map.prototype.value = function() {
    return this.current.value;
};

