var _Packages = {
		'package1': {
			title: '- no package -',
			description: 'Specify the banners yourself',
			banners: [
				{
					width: 468,
					height: 60
				}
			],
			is_default: true
		},
		'package2':{
			title: 'Standard',
			description: 'Includes the most popular banner sizes',
			banners: [
				{
					width: 125,
					height: 125
				},
				{
					width: 234,
					height: 60
				},
				{
					width: 468,
					height: 60
				},
				{
					width: 728,
					height: 90
				}
			]
		},
		'package3': {
			title: 'For Google',
			description: 'Includes all banner sizes to advertise with Google AdWords',
			banners: [
				{
					width: 120,
					height: 600
				},
				{
					width: 160,
					height: 600
				},
				{
					width: 200,
					height: 200
				},
				{
					width: 250,
					height: 250
				},
				{
					width: 300,
					height: 250
				},
				{
					width: 336,
					height: 280
				},
				{
					width: 468,
					height: 60
				},
				{
					width: 728,
					height: 90
				}
			]
		},
		'package4': {
			title: 'All in One',
			description: 'Almost all possible banner sizes including the ones for Google Adwords, Microsoft Advertising, AOL Media Networks and others',
			banners: [
				{ width: 88, height: 31},
				{ width: 120, height: 240},
				{ width: 120, height: 60},
				{ width: 120, height: 90},
				{ width: 120, height: 600},
				{ width: 160, height: 600},
				{ width: 180, height: 150},
				{ width: 200, height: 200},
				{ width: 234, height: 60},
				{ width: 240, height: 400},
				{ width: 250, height: 250},
				{ width: 300, height: 100},
				{ width: 300, height: 250},
				{ width: 300, height: 600},
				{ width: 336, height: 280},
				{ width: 380, height: 200},
				{ width: 468, height: 60},
				{ width: 728, height: 90}
			]
		}
	};

var _default_package = false;
var total = 1;

function initPage()
{
	initCookies();
	initForm();
	detectSafari();
	fill_gmt_offset();
	spamProtect();
}

function initForm()
{
	var _form = __$('order-form');
	var _banners = __$("banners");
	if(_form)
	{
		_form.onsubmit = function()
		{
			return isEmailFieldValid(__$('order-email'));
		}
	}
	var _more = __$("add-another-banner");
	var _first_banner = __$("first-banner");
	if(_more && _first_banner)
	{
		_first_banner.style.zIndex = 1000;
		//initDropDownDoubleInput(_first_banner);
		_more.href = "javascript:;";
		_more.onclick = function()
		{
			addBanner();
			return false;
		}
		var _banner_list = __$$(_banners, 'div', 'banner');
		if(_banner_list.length) {
			for(var i = 0; i < _banner_list.length; i++)
			{
				initBanner(_banner_list[i]);
			}
			calcPrice();
		}
	}

	initPackages();
	initDropDownDoubleInput(__$("package"));
	if(_default_package && !_banner_list.length)
	{
		_default_package._notshow = true;
		_default_package.onclick();
		_default_package._notshow = false;
	}

	var _ticket_form = __$('ticket-form');
	if(_ticket_form)
	{
		_ticket_form.onsubmit = function()
		{
			return isEmailFieldValid(__$('ticket-email')) && isCommentFieldFill(__$('comments'));
		}
	}

	var _client_ticket_form = __$('client-ticket-form');
	if(_client_ticket_form)
	{
		_client_ticket_form.onsubmit = function()
		{
			return isCommentFieldFill(__$('client-comments'));
		}
	}
}

var open_dd = false;
var _timeout = false;

function addBanner() {
	var _elem = null;
	var _first_banner = __$("first-banner");
	var _banners = __$("banners");
	if(_first_banner && _banners)
	{
		var _inner = _first_banner.innerHTML;
		_div = document.createElement('DIV');
		_div.className = 'banner';
		_div.innerHTML = _inner;
		//alert(element.parentNode.className);
		var _elem = _banners.appendChild(_div);
		initBanner(_elem);
	}
	calcPrice();
	return _elem;
}

function initBanner(_elem)
{
	var _first_banner = __$("first-banner");
	total++;
	_elem.style.zIndex = _first_banner.style.zIndex - total + 1;
	initDropDownDoubleInput(_elem);

	var _label_el = __$$(_elem,'label','banner-cnt');
	if(_label_el.length) {
		if(_label_el[0]) _label_el[0].htmlFor = 'l-banner'+ (total);
	}
	var _slabel_el = __$$(_elem,'label','hidden');
	if(_slabel_el.length) {
		if(_slabel_el[0]) _slabel_el[0].htmlFor = 'r-banner'+ (total);
	}

	var _del_el = __$$(_elem,'a','delete');
	if(_del_el[0])
	{
		_del_el[0].href = "javascript:;";
		_del_el[0].onclick = function()
		{
			var _parent = this.parentNode;
			_parent.parentNode.removeChild(_parent);
			if(!this._notcalc)
			{
				calcPrice();
			}
			return false;
		}
	}
}

function initDropDownDoubleInput(_el)
{
	if(_el)
	{
		var _inps = __$$(_el,'input');

		if(_el.id != "package")
		{
			if(_inps[0]) _inps[0].name = 'width['+ total +']';
			if(_inps[1]) _inps[1].name = 'height['+ total +']';
			if(_inps[0]) _inps[0].id = 'l-banner'+ total;
			if(_inps[1]) _inps[1].id = 'r-banner'+ total;

			if(_inps[4]) _inps[4].name = 'frames['+ total +']';
			if(_inps[2])
			{
				_inps[2].name = 'is_rounded['+ total +']';
				_inps[2].parentNode.htmlFor = _inps[2].id = 'rounded-'+ total;
			}
			if(_inps[3])
			{
				_inps[3].name = 'is_animated['+ total +']';
				_inps[3].parentNode.htmlFor = _inps[3].id = 'animated-'+ total;
			}
		}
		var _dd_el = __$$(_el,'div','select');
		if(_dd_el[0])
		{
			var _divs = __$$(_dd_el[0],'ul');
			if(_divs[0])
			{
				_divs[0].onmouseover = function()
				{
					open_dd = this;
					if(_timeout)
					{
						clearTimeout(_timeout);
					}
				}
				_divs[0].onmouseout = function()
				{
					_timeout = setTimeout('closeDiv()',200);
				}
			}
			var _as = __$$(_dd_el[0],'a');
			for(var i = 0; i < _as.length; i++)
			{
				_as[i].href = "javascript:;";
				if(i == 0)
				{
					_as[i].removeAttribute('href');
					if(_divs[0])
					{
						_as[i]._div = _divs[0];
					}
					_as[i].onclick = function()
					{
						if(this._div)
						{
							if(this._div.style.display != "block")
							{
								this._div.style.display = "block";
							}
							else
							{
								this._div.style.display = "none";
							}
						}
						return false;
					}
					_as[i].onmouseover = function()
					{
						if(this._div)
						{
							this._div.onmouseover();
						}
					}
					_as[i].onmouseout = function()
					{
						if(this._div)
						{
							this._div.onmouseout();
						}
					}
				}
				else
				{
					if(_dd_el[0].parentNode.id == "package")
					{
						_as[i]._close_a = _as[0];
						var _ems = __$$(_dd_el[0],'em');
						if(_ems[0])
						{
							_as[i]._em = _ems[0];
							_ems[0]._a = _as[0];
							_ems[0].onclick = function() {
								this._a.onclick();
								return false;
							};
							_ems[0].onmouseover = function(){this._a.onmouseover()};
							_ems[0].onmouseout = function(){this._a.onmouseout()};
						}
						if(_inps[0])
						{
							_as[i]._inp = _inps[0];
						}
						_as[i].onclick = function()
						{
							var _strongs = __$$(this,'strong');
							if(_strongs[0])
							{
								this._em.innerHTML = _strongs[0].innerHTML;
								if(this.rel)
								{
									var _mpackage = __$('m-package');
									if(_mpackage) {
										_mpackage.value = this.rel;
									}
								}
							}
							if(!this._notshow)
							{
								this._close_a.onclick();
							}
							var _dels = __$$(document,'a','delete');
							for(var i = 0; i < _dels.length; i++)
							{
								if(_dels[i].onclick)
								{
									_dels[i]._notcalc = true;
									_dels[i].onclick();
								}
							}
							total = 1;
							if(this.rel)
							{
								var _banners = _Packages[this.rel].banners;
								for(var i = 0; i < _banners.length; i++)
								{
									fillBannerLine(addBanner(), _banners[i]);
								}
							}
							calcPrice();
							return false;
						}
					}
					else
					{
						if(_inps[0]) _as[i]._winput = _inps[0];
						if(_inps[1]) _as[i]._hinput = _inps[1];
						_as[i]._close_a = _as[0];
						_as[i].onclick = function()
						{
							var _ems = __$$(this,'em');
							if(_ems.length > 1)
							{
								if(_ems[0]) this._winput.value = _ems[0].innerHTML;
								if(_ems[1]) this._hinput.value = _ems[1].innerHTML;
							}
							else
							{
								this._winput.value = '';
								this._hinput.value = '';
								try {this._winput.focus()} catch(e){}
							}
							this._close_a.onclick();
							return false;
						}
					}
				}
			}
		}
		if(_dd_el[1])
		{
			var _ul = document.createElement('ul');
			for(var i=2; i <= 12; i++)
			{
				var _li = document.createElement('li');
				var _a = document.createElement('a');
				_a.rel = i;
				_a.innerHTML = i + " frames";
				var __a = _li.appendChild(_a);
				_ul.appendChild(_li);
			}
			var __ul = _dd_el[1].appendChild(_ul);

			if(__ul)
			{
				__ul.onmouseover = function()
				{
					open_dd = this;
					if(_timeout)
					{
						clearTimeout(_timeout);
					}
				}
				__ul.onmouseout = function()
				{
					_timeout = setTimeout('closeDiv()',100);
				}
			}

                var _as = __$$(_dd_el[1],'a');
                for(var i = 0; i < _as.length; i++)
                {
                        _as[i].href = "javascript:;";
                        if(i == 0)
                        {
                            _as[i].removeAttribute('href');
                            if(__ul)
                            {
                                _as[i]._div = __ul;
                            }
                            _as[i].onclick = function()
                            {
                                if(this._div)
                                {
                                    if(this._div.style.display != "block")
                                    {
                                        this._div.style.display = "block";
                                    }
                                    else
                                    {
                                        this._div.style.display = "none";
                                    }
                                }
																return false;
                            }
                            _as[i].onmouseover = function()
                            {
                                if(this._div)
                                {
                                    this._div.onmouseover();
                                }

                            }
                            _as[i].onmouseout = function()
                            {
                                if(this._div)
                                {
                                    this._div.onmouseout();
                                }

                            }
                        }
           				else
                		{
                                var _em = __$$(_dd_el[1],'em','value');
                                var _input = __$$(_dd_el[1],'input');
                                if(_em[0]) _as[i]._em = _em[0];
                                if(_input[0]) _as[i]._input = _input[0];
                                _as[i]._close_a = _as[0];
                                _as[i].onclick = function()
                                {
                                    this._em.innerHTML = this.innerHTML;
                                    this._input.value = this.rel
                                    this._close_a.onclick();
                                    calcPrice();
																		return false;
                                }
                        }
                }
		}

		initAnimatedChecked(_el);
	}
}


function initLabels()
{
	var _banners = __$("banners");
	var _ls = __$$(_banners,'label','banner-cnt');
	for(var i = 0 ; i < _ls.length; i++)
	{
		if(_ls.length == 1)
		{
			_ls[i].innerHTML = "Banner";
		}
		else
		{
			if(i < 9)
			{
				_ls[i].innerHTML = "<span>0" + (i+1) +"</span> Banner";
			}
			else
			{
				_ls[i].innerHTML = "<span>" + (i+1) +"</span> Banner";
			}
		}
	}
	var _dels = __$$(_banners,'a','delete');
	if(_dels.length) {
		if(_dels.length > 1)
		{
			_dels[0].style.display = "block";
		}
		else
		{
			_dels[0].style.display = "none";
		}
	}
}

function initPackages()
{
	var _package = __$('package');
	if(_Packages && _package)
	{
		var _div_sels = __$$(_package,'div','select');
		if(_div_sels[0])
		{
			var _ul = document.createElement('ul');
			for(k in _Packages)
			{
				var _li = document.createElement('li');
				var _a = document.createElement('a');
				var _strong = document.createElement('strong');
				_strong.innerHTML = _Packages[k].title;
				_a.appendChild(_strong);
				_a.href = "#";
				_a.innerHTML += " " + _Packages[k].description;
				_a.rel = k;
				var __a = _li.appendChild(_a);
				_ul.appendChild(_li);
				if(_Packages[k].is_default) _default_package = __a;
			}
			_div_sels[0].appendChild(_ul);
		}
		var _mpackage = __$('m-package');
		var _em = __$$(_package, 'em');
		if(_mpackage && _mpackage.value && _em) {
			_em[0].innerHTML = _Packages[_mpackage.value]['title'];
		}
	}
}

function initAnimatedChecked(_el)
{
	var _inps = __$$(_el,'input');
	var _dd_el = __$$(_el,'div','select');
	if(_inps[3])
	{
		if(_dd_el[1])
		{
			_inps[3]._select = _dd_el[1];
		}
		_inps[3].onchange = _inps[3].onclick = function() {
			if(this._select)
			{
				if(this.checked)
				{
					this._select.style.visibility = 'visible';
				}
				else
				{
					this._select.style.visibility = 'hidden';
				}
			}
			calcPrice();
		}
	}
}


function fillBannerLine(_el,params)
{
var _inps = __$$(_el,'input');
	var _dd_el = __$$(_el,'div','select');
	if(_inps[0] && params.width) _inps[0].value = params.width;
	if(_inps[1] && params.height) _inps[1].value = params.height;
	if(_inps[2])
	{
		if(params.is_rounded)
			_inps[2].checked = true;
		else
			_inps[2].checked = false;
	}
	if(_inps[3])
	{
		if(params.is_animated)
		{
			_inps[3].checked = true;
			if(_dd_el[1]) _dd_el[1].style.visibility = "visible";
		}
		else
		{
			_inps[3].checked = false;
			if(_dd_el[1]) _dd_el[1].style.visibility = "hidden";
		}

		if(params.frames && _inps[4] && _dd_el[1])
		{
			_inps[4].value = params.frames;
			var _ems = __$$(_dd_el[1],'em','value');
			if(_ems[0])
			{
				_ems[0].innerHTML = params.frames + " frames";
			}
		}
	}
}


function calcPrice()
{
	var _banners = __$('banners');
	var _p_spans = __$$(_banners, 'span', 'price');
	var _total_span = __$('total-price');
	var _total = 0;
	if(_p_spans.length > 0 && _total_span)
	{
		for(var i = 0; i < _p_spans.length; i++)
		{
			var _inps = __$$(_p_spans[i].parentNode,'input');
			if(_inps[3] && _inps[3].checked && _inps[4])
			{
				_total += (parseInt(_Price['default']) + (parseInt(_inps[4].value) - 1) * parseInt(_Price['perframe']));
				_p_spans[i].innerHTML = "$" + (parseInt(_Price['default']) + (parseInt(_inps[4].value) - 1) * parseInt(_Price['perframe']));
			}
			else
			{
				_total += parseInt(_Price['default']);
				_p_spans[i].innerHTML = "$" + parseInt(_Price['default']);
			}
		}
		_total_span.innerHTML = "$" + _total;
	}
	initLabels();
}

function closeDiv()
{
	if(open_dd)
	{
		open_dd.style.display = 'none';
	}
}

function spamProtect() {
	var _buttonOrder = document.getElementById('place-order-button');
	if(_buttonOrder) {
		_buttonOrder.onclick = function() {
			document.getElementById('spam_protect_f2').value = 'RightBanners!';
		}
	}
	var _buttonMessage = document.getElementById('post-message-button');
	if(_buttonMessage) {
		_buttonMessage.onclick = function() {
			document.getElementById('spam_protect').value = 'RightBanners!';
		}
	}
}

function __$(id){
	return document.getElementById(id);
}

function __$$(_elem,_tag,_class)
{
	var _return = [];
	if(_elem)
	{
		var _els = _elem.getElementsByTagName(_tag);
		for(var i = 0; i < _els.length; i++)
		{
			if(_class)
			{
				if(_els[i].className.indexOf("" + _class) != -1)
				{
					_return[_return.length] = _els[i];
				}
			}
			else
			{
				_return[_return.length] = _els[i];
			}
		}
	}
	return _return;
}

function isEmailFieldValid(object)
{
	if (!object) return false;
	var string = object.value.trim();
	if (string == '' || !string.match(new RegExp('^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$')))
	{
		alert("Please specify a valid email address.");
		try {object.focus()} catch(e){}
		return false;
	}
	return true;
}

function isCommentFieldFill(object)
{
	if (!object) return false;
	var string = object.value;
	if (string == '')
	{
		alert("Please fill the comments field.");
		try {object.focus()} catch(e){}
		return false;
	}
	return true;
}

function fill_gmt_offset()
{
	gmt_offset_fields = __$$(document, 'input', 'gmt_offset_field');
	for(var i = 0; i < gmt_offset_fields.length; i++)
	{
		var d = new Date();
		var n_winter = new Date(d.getFullYear(), 0, 1);
		var n_sommer = new Date(d.getFullYear(), 6, 1);
		var n_winter_gmt_offset = -n_winter.getTimezoneOffset();
		var n_sommer_gmt_offset = -n_sommer.getTimezoneOffset();
		if(n_winter_gmt_offset < n_sommer_gmt_offset)
		{
			gmt_offset = n_winter_gmt_offset;
		}
		else
		{
			gmt_offset = n_sommer_gmt_offset;
		}
		gmt_offset_fields[i].value = gmt_offset;
	}
}

function detectSafari()
{
	if (navigator.appVersion.indexOf("Safari") != -1){
		if (!window.getComputedStyle) document.body.className += " safari2";
		else document.body.className += " safari3";
	}
}

function initCookies() {
	var referrer = new String(document.referrer);
	referrer = (referrer.indexOf(document.location.host) != -1) ? "<direct>" : document.referrer;

	if(!getCookie("ref1")) {
		setCookie("ref1", referrer);
		setCookie("ref2", "<first access>");
	}
	else if(referrer != "local") {
		setCookie("ref2", referrer);
	}
}

function setCookie(name, value) {
	var date = new Date();
	date = new Date(date.getFullYear(), date.getMonth() + 3, date.getDate());
	document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString();
}

function getCookie(name) {
	var cookies = document.cookie.split("; ");
	for(var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i].split("=");
		if(name == cookie[0]) {
			return unescape(cookie[1]);
		}
	}

	return null;
}

String.prototype.trim = function (chars) {
	var t = this.ltrim(chars).rtrim(chars);
	return this.ltrim(chars).rtrim(chars);
}

String.prototype.ltrim = function (chars) {
	chars = chars || "\\s";
	return this.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

String.prototype.rtrim = function (chars) {
	chars = chars || "\\s";
	return this.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

if (window.addEventListener){
	window.addEventListener("load", initPage, false);
}
else if (window.attachEvent && !window.opera){
	window.attachEvent("onload", initPage);
}
