/*
``````````````````````````````````````````````````````
Autex Industries
Common Javascript Test

Created by Seven
http://www.seven.co.nz/
``````````````````````````````````````````````````````
*/

/* CONSTANTS
 */
var product_pages = { abo: "about", env: "environment", gal: "gallery", vie: "swatches", sto: "stockists", pro: "enquiry" };


/* VARIABLES
 */
var opensection;
var opensectionid;
var newsarticles = {};
var openarticleid;
var cachedcontent = {};


/* FUNCTIONS
 */
// Additional JQuery scripts
jQuery.preloadImages = function() {
	for(var i=0; i<arguments[0].length; i++) {
		jQuery("<img>").attr("src", arguments[0][i]);
	}
}

// Common functions
function validEmail(email) {
	var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	return filter.test(email);
}
function isIE6() {
	var isMSIE = $.browser.msie;
	var majVersion = $.browser.version.substr(0, 1);
	return ((isMSIE) && (majVersion < 7));
}
function isIE7() {
	var isMSIE = $.browser.msie;
	var majVersion = $.browser.version.substr(0, 1);
	return ((isMSIE) && (majVersion < 8));
}
function toStep1() {
	// Animate layout
	$('#tit-step1').toggleClass('closed');
	if (isIE6()) {
		$('.list').toggle();
		$('.form').toggle();
	} else {
		$('.list').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
		$('.form').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
	}
}
function toStep2() {
	// Update list of swatches
	var list = [];
	$('.list input:checked').each(function() {
		list.push($(this).val());
	});
	$('#swatchlist').val(list.join(', '));
	$('#swatch_sum p').html(list.join(', ') + '<br /><a href="javascript:toStep1();" tabindex="3">Edit this list</a>');
	
	// Check form is ready to send
	if (list.length == 0) {
		jAlert('Please select a swatch first...', 'No Swatch Selected...');
	} else {
		// Animate layout
		$('#tit-step1').toggleClass('closed');
		if (isIE6()) {
			$('.list').toggle();
			$('.form').toggle();
		} else {
			$('.list').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
			$('.form').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
		}
	}
}

function toggleStep1Step2() {
	// Check form is ready to send
	if (list.length == 0) {
		jAlert('Please select a swatch first...', 'No Swatch Selected...');
	} else {
		// Animate layout
		$('#tit-step1').toggleClass('closed');
		if (isIE6()) {
			$('.list').toggle();
			$('.form').toggle();
		} else {
			$('.list').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
			$('.form').slideToggle({ duration: 500, easing: 'easeInOutCubic' });
		}
		// Update page height
		
		adjustProductHeight();
	}
}
function orderSwatches() {
	// Check fields are filled correctly
	var msg = [];
	if (!validEmail($('#f-email').val())) {
		msg.push("Please enter a valid <em>Email Address</em>");
	}
	if ($('#f-for option:selected').val() == "") {
		msg.push("Please select <em>Who</em> this is for");
	}
	if ($('#f-address').val() == "") {
		msg.push("Please enter a <em>Physical Address</em>");
	}
	if (msg.length > 0) {
		jAlert(msg, 'Order Form Incomplete...');
		return;
	}
	
	// Send form information
	var copy = $('#f-copy:checked').val();
	if (copy == null) copy = 'no';
	$.post("/form/order-swatches", { 
		division: $('#f-division').val(),
		productid: $('#f-productid').val(), 
		countrycode: $('#f-countrycode').val(), 
		list: $('#swatchlist').val(), 
		email: $('#f-email').val(), 
		whofor: $('#f-for option:selected').val(), 
		address: $('#f-address').val(), 
		comments: $('#f-comments').val(), 
		emailcopy: copy });
	
	// Animate layout
	$('#tit-step2').addClass('closed');
	if (isIE6()) {
		$('#tit-step1').hide();
		$('.form').hide();
		$('.thanks').show();
	} else {
		$('#tit-step1').slideUp({ duration: 500, easing: 'easeInOutCubic' });
		$('.form').slideUp({ duration: 500, easing: 'easeInOutCubic' });
		$('.thanks').slideDown({ duration: 500, easing: 'easeInOutCubic' });
	}
}
function resetSwatches() {
	// Reset all form fields
	$('.list input:checked').each(function() {
		$(this).attr('checked','');
	});
	
	// Animate layout
	$('#tit-step1').removeClass('closed');
	if (isIE6()) {
		$('#tit-step1').show();
		$('.list').show();
		$('.thanks').hide();
	} else {
		$('#tit-step1').slideDown({ duration: 500, easing: 'easeInOutCubic' });
		$('.list').slideDown({ duration: 500, easing: 'easeInOutCubic' });
		$('.thanks').slideUp({ duration: 500, easing: 'easeInOutCubic' });
	}
}
function sendGeneralEnquiry() {
	// Check fields are filled correctly
	var msg = [];
	var methodvalue = "";
	
	if ($('#f-name').val() == "") {
		msg.push("Please enter your <em>Name</em>");
	}
	if ($('#f-company').val() == "") {
		msg.push("Please enter the name of your <em>Company</em>");
	}
	var method = $('#f-gmethod option:selected').val();
	if (method == "") {
		msg.push("Please select a <em>Method</em> for Autex to contact you");
	} else {
		if (method == 'email') {
			methodvalue = $('#f-email').val();
			if (!validEmail(methodvalue)) {
				msg.push("Please enter a valid <em>Email Address</em>");
			}
		} else if (method == 'phone') {
			methodvalue = $('#f-phone').val();
			if (methodvalue == "") {
				msg.push("Please enter a <em>Phone Number</em>");
			}
		} else if (method == 'fax') {
			methodvalue = $('#f-fax').val();
			if (methodvalue == "") {
				msg.push("Please enter a <em>Fax Number</em>");
			}
		}
	}
	var businesstype = [];
	$('#field-business input:checked').each(function() {
		businesstype.push($(this).val());
	});
	if (($('#f-otherbusiness').val() == "") || ($('#f-otherbusiness').val() == $('#f-otherbusiness').attr('title'))) {
		if (businesstype.length == 0) {
			msg.push("Please define your <em>Type of Business</em>");
		}
	} else {
		businesstype.push($('#f-otherbusiness').val());
	}
	if ($('#f-subject').val() == "") {
		msg.push("Please enter the <em>Subject</em> of this Enquiry");
	}
	if ($('#f-comments').val() == "") {
		msg.push("Please enter some <em>Comments</em> to go with this Enquiry");
	}
	if (msg.length > 0) {
		jAlert(msg, 'Enquiry Form Incomplete...');
		return;
	}
	
	// Send form information
	var copy = $('#f-copy:checked').val();
	if (copy == null) copy = 'no';
	$.post("/form/general-enquiry", { 
		division: $('#f-division').val(), 
		countrycode: $('#f-countrycode').val(), 
		name: $('#f-name').val(), 
		company: $('#f-company').val(), 
		method: method, 
		methodvalue: methodvalue, 
		business: businesstype.join(', '), 
		subject: $('#f-subject').val(), 
		comments: $('#f-comments').val(), 
		productenquiry: $('#f-productenquiry').val(), 
		emailcopy: copy });
	
	// Animate layout
	if (isIE6()) {
		$('.form-thanks').show();
		$('.form-fill').hide();
	} else {
		$('.form-thanks').slideDown({ duration: 500, easing: 'easeInOutCubic' });
		$('.form-fill').slideUp({ duration: 500, easing: 'easeInOutCubic' });
	}
}
function sendExportEnquiry() {
	// Check fields are filled correctly
	var msg = [];
	
	if ($('#f-name').val() == "") {
		msg.push("Please enter your <em>Name</em>");
	}
	if ($('#f-company').val() == "") {
		msg.push("Please enter the name of your <em>Company</em>");
	}
	var method = $('#f-method option:selected').val();
	if (method == "") {
		msg.push("Please select a preferred <em>Contact Method</em>");
	} else {
		if (method == 'email') {
			if (!validEmail($('#f-email').val())) {
				msg.push("Please enter a valid <em>Email Address</em>");
			}
		} else if (method == 'phone') {
			if ($('#f-phone').val() == "") {
				msg.push("Please enter a <em>Phone Number</em>");
			}
		} else if (method == 'fax') {
			if ($('#f-fax').val() == "") {
				msg.push("Please enter a <em>Fax Number</em>");
			}
		} else {
			if ($('#f-method-other').val() == "") {
				msg.push("Please enter an <em>Alternate Contact Method</em>");
			}
		}
	}
	if ($('#f-address').val() == "") {
		msg.push("Please enter a <em>Physical Address</em>");
	}
	if ($('#f-country').val() == "") {
		msg.push("Please enter your <em>Country</em>");
	}
	var businesstype = [];
	$('#field-business input:checked').each(function() {
		businesstype.push($(this).val());
	});
	if (($('#f-otherbusiness').val() == "") || ($('#f-otherbusiness').val() == $('#f-otherbusiness').attr('title'))) {
		if (businesstype.length == 0) {
			msg.push("Please define your <em>Type of Business</em>");
		}
	} else {
		businesstype.push($('#f-otherbusiness').val());
	}
	var divisions = [];
	$('#field-products input:checked').each(function() {
		divisions.push($(this).val());
	});
	if (($('#f-otherproducts').val() == "") || ($('#f-otherproducts').val() == $('#f-otherproducts').attr('title'))) {
		if (divisions.length == 0) {
			msg.push("Please define the <em>Products you are interested in</em>");
		}
	} else {
		divisions.push($('#f-otherproducts').val());
	}
	if ($('#f-requirements').val() == "") {
		msg.push("Please enter your <em>Requirements</em>");
	}
	if (msg.length > 0) {
		jAlert(msg, 'Export Form Incomplete...');
		return;
	}
	
	// Send form information
	var copy = $('#f-copy:checked').val();
	if (copy == null) copy = 'no';
	var other = $('#f-method-other').val();
	if (other == $('#f-method-other').attr('title')) other = '';
	
	$.post("/form/export-enquiry", { 
		countrycode: $('#f-countrycode').val(), 
		name: $('#f-name').val(), 
		company: $('#f-company').val(), 
		method: method, 
		email: $('#f-email').val(), 
		phone: $('#f-phone').val(), 
		fax: $('#f-fax').val(), 
		other: other,  
		website: $('#f-website').val(), 
		address: $('#f-address').val(), 
		country: $('#f-country').val(), 
		business: businesstype.join(', '), 
		divisions: divisions.join(', '), 
		requirements: $('#f-requirements').val(), 
		productref: $('#ref-product').val(), 
		emailcopy: copy });
	
	// Animate layout
	if (isIE6()) {
		$('.form-thanks').show();
		$('.form-fill').hide();
	} else {
		$('.form-thanks').slideDown({ duration: 500, easing: 'easeInOutCubic' });
		$('.form-fill').slideUp({ duration: 500, easing: 'easeInOutCubic' });
	}
}
function closeNewsArticle(articleid) {
	// Close article
	$('#' +articleid).removeClass('open');
	$('#' +articleid+ ' p:first').html(newsarticles[articleid].substr(0, 130) + "...");
	$('#' +articleid+ ' p:not(:first)').hide();
	$('#' +articleid+ ' h4').hide();
	$('#' +articleid+ ' .gimages').hide();
	$('#' +articleid+ ' .links').hide();
	
	// Update internal record
	if (openarticleid == articleid) openarticleid = undefined;
	
	// Update button
	$('#' +articleid+ ' .morelink').html('Read More');
	$('#' +articleid+ ' .morelink').unbind();
	$('#' +articleid+ ' .morelink').click(function() {
		openNewsArticle(articleid);
		return false;
	});
}
function openNewsArticle(articleid) {
	// Close any other open article
	if ((openarticleid != undefined) && (openarticleid != articleid)) {
		closeNewsArticle(openarticleid);
	}
	
	// Open this article
	$('#' +articleid).addClass('open');
	$('#' +articleid+ ' p:first').html(newsarticles[articleid]);
	$('#' +articleid+ ' p').show();
	$('#' +articleid+ ' h4').show();
	$('#' +articleid+ ' .gimages').show();
	$('#' +articleid+ ' .links').show();
	
	// Update internal record
	openarticleid = articleid;
	
	// Update button
	$('#' +articleid+ ' .morelink').html('Close');
	$('#' +articleid+ ' .morelink').unbind();
	$('#' +articleid+ ' .morelink').click(function() {
		closeNewsArticle(articleid);
		return false;
	});
}
function setOpenSectionEvents(sectionid) {
	$(sectionid).each(function() {
		$(this).click(function() {
			// Get unique product id
			var strid = $(this).parent().parent().prev().prev().html() +' : '+ $(this).html();
			
			// Close previous section
			if (opensectionid != '') {
				$(opensection).parent().toggleClass('open');
				$(opensection).next().slideToggle({ duration: 500, easing: 'easeInOutCubic' }); 
			}
			// Toggle this section
			if (opensectionid != strid) {
				$(this).parent().toggleClass('open');
				$(this).next().slideToggle({ duration: 500, easing: 'easeInOutCubic' });
				opensectionid = strid;
				opensection = $(this);
			} else {
				opensectionid = opensection = '';
			}
			return false;
		});
	});
}
function getProductPageContent(country, product, page) {
	$.get("/retrieve-page/"+country+"/"+product+"/"+page, function(data) {
		// Store HTML
		cachedcontent[page] = data;
		// Find images in HTML
		var images = [];
		
		// Bad Pattern
		var patterns = [/url\(.*?\.jpg|gif|png/gi, /rc=\".*?\.jpg|gif|png/gi];
		
		for(var i=0; i < patterns.length; i++) {
			var matches = data.match(patterns[i]);
			if (matches != null) {
				for(var j=0; j < matches.length; j++) {
					images.push(matches[j].substr(4));
				}
			}
		}
		// Preload
		$.preloadImages(images);
	});
}
function viewNewsArchive() {
	$('.articles .butwrap').hide();
	$('.articles .archive').slideDown();
}
function setupFormFieldEvents() {
	// Textfield
	$('.textfield input').each(function() {
		$(this).focus(function() { 
			$(this).css({ backgroundPosition: 'left bottom' });
		});
		$(this).blur(function() { 
			$(this).css({ backgroundPosition: 'left top' });
		});
	});
	$('input.defvalue').each(function() {
		$(this).addClass('def');
		$(this).focus(function() { 
			$(this).css({ backgroundPosition: 'left bottom' });
			if ($(this).val() == $(this).attr('title')) {
				$(this).removeClass('def');
				$(this).val('');
			}
		});
		$(this).blur(function() { 
			$(this).css({ backgroundPosition: 'left top' });
			if ($(this).val() == '') {
				$(this).addClass('def');
				$(this).val($(this).attr('title'));
			}
		});
	});
	// Textarea
	$('.textarea textarea').each(function() {
		$(this).focus(function() { $(this).parent().css({ backgroundPosition: 'left bottom' }) });
		$(this).blur(function() { $(this).parent().css({ backgroundPosition: 'left top' }) });
	});
	// Select
	$('.select select').each(function() {
		$(this).mouseover(function() { $(this).parent().css({ backgroundPosition: 'left bottom' }) });
		$(this).focus(function() { $(this).parent().css({ backgroundPosition: 'left bottom' }) });
		$(this).mouseout(function() { $(this).parent().css({ backgroundPosition: 'left top' }) });
		$(this).blur(function() { $(this).parent().css({ backgroundPosition: 'left top' }) });
		$(this).change(function() {
			var sel = $(this).children('option:selected');
			var val = $(sel).val();
			$(this).prev().html($(sel).html());
		});
	});
	
	// General Enquiry
	$('#f-gmethod').change(function() {
		var options = ['email','phone','fax'];
		var val = $(this).children('option:selected').val();
		for(var i=0; i < options.length; i++) {
			// Selected
			if (options[i] == val) {
				$('#method-' +val).slideDown({ duration: 300, easing: 'easeOutCubic' });
			}
			// Not selected
			else {
				$('#method-' +options[i]).hide();
			}
		}
		if (val == 'email') {
			$('#field-copy').show();
		} else {
			$('#field-copy').hide();
		}
	});
}


/* EVENTS
 */

// On Window Load
$(document).ready(function() {
	// Form field events
	setupFormFieldEvents();
	
	// Preload product content
	$('#menu').each(function() { 
		var pages = [];
		$('#menu li').find('a').each(function() {
			pages.push($(this).html().substr(0,3).toLowerCase());
		});
		var product = $('#container').attr('class').substr(9);
		// Get each page content
		var country = $('#colr h1 a').attr('href').substr(1, 2);
		for(var i=0; i < pages.length; i++) {
			getProductPageContent(country, product, pages[i]);
		}
		// Preload common images
		$.preloadImages(['/img/form/bg-menu.jpg','/img/but/autex-gallery.png','/img/but/backto-step1.png','/img/but/next-step.png','/img/icon/item-toggle.png','/img/icon/matrix-open.png']);
	});
	// Product menu
	$('#menu li').find('a').click(function() {
		// Update menu
		$('#menu .sel').removeClass('sel')
		$(this).parent().addClass('sel')
		
		// Get content
		var page = $(this).html().substr(0,3).toLowerCase();
		var html = cachedcontent[page];
		// Set new content
		$('#page-content').html(html);
		// Fade in
		if (!$.browser.msie) {
			$('#page-content').hide();
			$('#page-content').fadeIn(300);
		}
		setupFormFieldEvents();
		
		// Adjust page content
		$('.swatches .form').hide();
		$('.swatches .thanks').hide();
		tb_init('a.thickbox');
		setOpenSectionEvents('.country .opt');
		
		// Track users with Analytics
		try {
			if (pageTracker) {
				var url = window.location + '';
				var parts = url.substr(url.search(/autexindustries/) + 20).split('/');
				pageTracker._trackPageview("/" +parts[0]+ "/" +parts[1]+ "/" +parts[2]+ "/" +product_pages[page]);
			}
		} catch(err) {}
		
		return false;
	});
	
	// News Articles init
	$('.news li.article').each(function() {
		// Get news article id
		var id = $(this).attr('id');
		// Store first full paragraphs
		newsarticles[id] = $(this).find('p:first').html();
		
		// Shorten first paragraph
		$(this).find('p:first').html(newsarticles[id].substr(0, 130) + "...");
		// Hide everything
		$(this).find('p').hide();
		$(this).find('h4').hide();
		$(this).find('.images').hide();
		$(this).find('.links').hide();
		$(this).find('p:first').show();
		
		// Button events
		$(this).find('.morelink').click(function() {
			openNewsArticle(id);
			return false;
		});
		
		// Open selected article
		if ($(this).hasClass('selected')) {
			openNewsArticle(id);
		}
	});
	
	// Export Enquiry
	$('#f-method').change(function() {
		var options = ['email','phone','fax','other'];
		var val = $(this).children('option:selected').val();
		if (val == 'email') {
			$('#field-copy').show();
		} else {
			$('#field-copy').hide();
		}
		for(var i=0; i < 4; i++) {
			// Selected
			if (options[i] == val) {
				if (i < 3) {
					$('#field-' +options[i]).prev().find('em').html('(required)');
				} else {
					$('#field-method-other').prev().addClass('nomargin');
					$('#field-method-other').slideDown({ duration: 300, easing: 'easeOutCubic' });
				}
			}
			// Not selected
			else {
				if (i < 3) {
					$('#field-' +options[i]).prev().find('em').html('');
				} else {
					$('#field-method-other').prev().removeClass('nomargin');
					$('#field-method-other').hide();
				}
			}
		}
	});
	
	// Matrix filter button
	$('#gobut').click(function() {
		var division = $('#f-division').children('option:selected').val();
		if (division == '') {
			$('.division').each(function() {
				$(this).show();
			});
		} else {
			$('.division').each(function() {
				$(this).hide();
			});
			$('.'+division).each(function() {
				$(this).show();
			});
		}
		return false;
	});
	
	// Matrix Opera fix
	if ($.browser.opera) {
		if ($('#filterby').html() != undefined) {
			$('#division-select').css('background', 'none');
		}
	}
	
	// Country & Matrix sections
	setOpenSectionEvents('.country .opt');
	setOpenSectionEvents('.matrix .division .opt');
});