/********************************
CONTACT FORM
********************************/
ContactForm = Class.create({
	initialize: function(){
		this.cont = "";
		overlay = new Element('div', {'class':'contact-overlay'});
		win = new Element('div', {id:'contact-window', 'class': 'pngFix'});
		container = new Element('div', {id:'contact-container'});
		this.currentDimensions = document.viewport.getDimensions();
		//var container = this.container;
		closeBtn = new Element('a',{id:'contact-close-btn', 'class': 'pngFix'}).update("close");
		$(document.body).insert({bottom:container});
		
		if ($(overlay)) {
			Event.observe(window,"resize",this.resize.bind(this));
			Event.observe(window,"scroll",this.reposition.bind(this));
		}
		
	},
	show: function(element){
		this.close();
		cont = element;
		this.newDimensions = document.viewport.getDimensions();
		var vso = document.viewport.getScrollOffsets();
		$(container).appendChild($(overlay));
		this.win = $(container).appendChild($(win));
		this.win.insert({bottom:($(cont))});
		this.win.insert({bottom:($(closeBtn))});
		$(closeBtn).observe('click', this.close.bind(this));
		$(win).setStyle({
			top:vso.top + 50 +"px",
			left: String((document.viewport.getWidth()/2) - ($(win).getWidth()) + ($(win).getWidth()/2)) + 'px'
		});
		$(overlay).setStyle({
			width:this.newDimensions.width+"px",
			height:this.newDimensions.height+"px",
			top:vso.top+"px",
			left:vso.left+"px"
		});
		
	},
	
	resize: function(){
		this.newDimensions = document.viewport.getDimensions();
		var vso = document.viewport.getScrollOffsets();
		$(overlay).setStyle({
			width:this.newDimensions.width+"px",
			height:this.newDimensions.height+"px"
		});
		$(win).setStyle({
			top:vso.top + 50 +"px",
			//top : String((document.viewport.getHeight()/2) - ($(win).getHeight()) + ($(win).getHeight()/2)) + 'px',
			left: String((document.viewport.getWidth()/2) - ($(win).getWidth()) + ($(win).getWidth()/2)) + 'px'
		});
		this.currentDimensions = this.newDimensions;
	},
	
	reposition:function(){
		var vso = document.viewport.getScrollOffsets();
		$(overlay).setStyle({
			top:vso.top+"px",
			left:vso.left+"px"
		});
		$(win).setStyle({
			top:vso.top + 50 +"px",
			left: String((document.viewport.getWidth()/2) - ($(win).getWidth()) + ($(win).getWidth()/2)) + 'px'
		});
	},
	
	close: function(e){
		if(e) e.stop();
		$(container).childElements().invoke('remove');
		$(win).childElements().invoke('remove');
	}
});

showContact = function(){
	var url = 'form.html' + '?' + '&' + new Date().getTime();
	var contactform = new Element('div', {id:'contact-contents', 'class': 'clearfix'}).update("Loading Contact Form, please wait...");
	var updateForm = new Ajax.Updater('contact-contents', url, {
		method: 'get', 
		evalScripts: 'true',
		onComplete: function(){
			validateForm = new Validation('contact-form', {immediate: true, onSubmit: false});
		}
	});
	contact.show(contactform); 	
}

prepForm = function(){
	if (validateForm.validate()) {
		sendAjaxForm();
    }
}

sendAjaxForm = function(){     
	var oOptions = {  
			method: "POST",  
			parameters: Form.serialize("contact-form"),
			requestHeaders: {Accept: 'application/json'},
			asynchronous: true,  
			onFailure: function (oXHR) {  
				$('feedback').update(oXHR.statusText);  
			},  
			onLoading: function (oXHR) {  
				$('feedback').update('Sending data ... <img src="/img/ajax-loader.gif" title="Loading..." alt="Loading..." />');  
			},                            
			onSuccess: function(oXHR) {
			    updateFormAndFinchConversion();
			}                 
	};  
	var oRequest = new Ajax.Updater({success: oOptions.onSuccess.bindAsEventListener(oOptions)}, "/control/contact", oOptions);             
} 

doContact = function () {
    new Ajax.Request('contact', {
        asynchronous: false,
        onSuccess: function(transport) {
            var data = transport.responseText.evalJSON(true);
            name = data.name;
            updatePage();
        }, parameters: $('contact-form').serialize(), requestHeaders: {Accept: 'application/json'}
        
    });
}

function updateFormAndFinchConversion(){
	$('feedback').update("Thank you for your interest in HotWax Media.  We will be back with you ASAP to follow up on your comments.<br /><br/>Best regards,<br /><img src='/img/signature.gif' alt='The HotWax Team'/>");
    $('feedback').insert({bottom: '<script> JBC.trackConversion("15","125","Contact us form");</script>'})
    trackFinchConversion();
    $('contact-form').reset();
}

function trackFinchConversion() {
	ifrm = new Element('IFRAME');
    var aurl = 'http://www.hotwaxmedia.com/finch/iconversion.html' + '?' + Math.random();
    ifrm.setAttribute("src", aurl);
    ifrm.absolutize();
    $(ifrm).setStyle({
    	width: 1 + "px",
    	height: 1 + "px",
    	top: -9999 + "px",
    	left:-9999 + "px"
	});
    $(document.body).appendChild(ifrm);
}

/********************************
VALIDATION
********************************/
var Validator = Class.create({
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
});
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
};
var Validation = Class.create({
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) {
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
});
Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'inline';
				} else {
					new Effect.Appear(advice, {duration : 0.5 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});
Validation.add('IsEmpty', '', function(v) {
	return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
});
Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
	}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
	}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
	}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
	}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
	}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
	}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
	}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
	}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
	}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
		return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
	}],
	['validate-selection', 'Please make a selection', function(v,elm){
		return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
	}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
	}]
]);

/********************************
GLOBAL SEARCH HINT TEXT
********************************/
function initSearch(){
    var methods = {
        defaultValueActsAsHint: function(element){
            element = $(element);
            element._default = element.value;
            return element.observe('focus', function(){
                if(element._default != element.value) return;
                element.removeClassName('hint').value = '';
            }).observe('blur', function(){
                if(element.value.strip() != '') return;
                element.addClassName('hint').value = element._default;
            }).addClassName('hint');
        }
    };
    $w('input textarea').each(function(tag){ Element.addMethods(tag, methods) });
}
initSearch();

document.observe('dom:loaded', function(){
    $('s').defaultValueActsAsHint();	 
});

/********************************
URL VARIABLES
********************************/
function getQueryVariable(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];
	    }
	}
} 

/********************************
FLASH
********************************/
var Swiff = Class.create({
	options: {
		id: null,
		height: '100%',
		width: '100%',
		container: null,
		properties: {},
		params: {
			quality: 'high',
			allowScriptAccess: 'always',
			wMode: 'transparent',
			swLiveConnect: true
		},
		callBacks: {},
		vars: {}
	},

	toElement: function(){
		return this.object;
	},

	initialize: function(path, options){
		this.instance = 'Swiff_' + new Date().getTime();

		this.setOptions(options);
		options = this.options;
		var id = this.id = options.id || this.instance;
		var container = $(options.container);

		Swiff.CallBacks[this.instance] = {};

		var params = options.params, vars = options.vars, callBacks = options.callBacks;
		var properties = Object.extend({height: options.height, width: options.width}, options.properties);

		var self = this;

		for (var callBack in callBacks){
			Swiff.CallBacks[this.instance][callBack] = (function(option){
				return function(){
					return option.apply(self.object, arguments);
				};
			})(callBacks[callBack]);
			vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
		}

		params.flashVars = Hash.toQueryString(vars);
		if (Prototype.Browser.IE){
			properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
			params.movie = path;
		} else {
			properties.type = 'application/x-shockwave-flash';
			properties.data = path;
		}
		var build = '<object id="' + id + '"';
		for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
		build += '>';
		for (var param in params){
			if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
		}
		build += '</object>';
		this.object =  ((container) ? container.update() : new Element('div')).update(build).firstChild;
	},
	
	setOptions: function(options) {
	  this.options = Object.extend(this.options, options);
	},

	replaces: function(element){
		element = $(element, true);
		element.parentNode.replaceChild(this.toElement(), element);
		return this;
	},

	inject: function(element){
		$(element, true).appendChild(this.toElement());
		return this;
	},

	remote: function(){
		return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments));
	}

});

Swiff.CallBacks = {};

Swiff.remote = function(obj, fn){
	var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
	return eval(rs);
};

/********************************
INIT
********************************/
Event.observe(window, 'load', function() {
    contact = new ContactForm();
	$('contactus').observe('click', function(e){ e.stop(); showContact(); });
	$$('.showContact').invoke('observe','click', function(e){ e.stop(); showContact(); });
	var isContact = getQueryVariable("contact");
	if(isContact == "open") {
		showContact();
	}
});

Event.observe(window, 'load', function() {
	var isContact = getQueryVariable("contact");
	if(isContact == "open") {
		showContact();
	}
});

