/**
 * 
 */

$(document).ready(function(){	
	var prop_time_id; //global
	$('body').data('timeouts', new Array());
	$('#hover_area').mouseleave(function(){
		var vis_rollers = $(".rollover_stats");
		vis_rollers.fadeOut();
		vis_rollers.each(function(){
			$(this).parent().css("z-index", Number($(this).parent().attr("zi")));
		});
		stopSlideshows();
	});
	$('.gallery_link').mouseenter(function(){
		stopSlideshows();
		var li_sel = $(this).parent().parent();
		var img_select = $(this).children("img");
		var vis_rollers = $(".rollover_stats:visible");
		vis_rollers.fadeOut('fast', function(){
			$(this).parent().css("z-index", Number($(this).parent().attr("zi")));
		});
		li_sel.css("z-index", Number(li_sel.attr("zi"))+1000);
		li_sel.children(".rollover_stats").show('slide',{direction:'left'},400);
		prop_time_id = setTimeout(function(){start_gallery(img_select);}, 1500);		
	});
	$('.gallery_link').mouseleave(function(){
		clearTimeout(prop_time_id);
	});
	$('.gib_email, .gib_contact').click(function(){
		$('#contact_div').modal({opacity: 70, containerId:'simplemodal-container-white'});
		

	});
});
function stopSlideshows(){
	var timeouts = $("body").data("timeouts");
	for (var i in timeouts){
		clearTimeout(timeouts[i]);
	}
	$("body").data("timeouts", new Array());	
}
function start_gallery(element)
{
	var gid = element.parent().attr("id");
	var img_data = $("body").data("imgs");
	var img_id = Number(element.attr("id").replace("img", ""));//get the showing pic_id in the array
	var currIndex = $.inArray(img_id, img_data[gid]['img']);
	if (currIndex != -1) {
		//iterate to next id in array
		var nextIndex = currIndex + 1;
		var desIndex = img_data[gid]['img'].length - 1;
		if (nextIndex > desIndex){
			//need to start from beginning
			nextIndex = 0;
		}
		var nextImage = img_data[gid]['img'][nextIndex];
		//if browser does not support the image object, exit.
		if (!document.images) return
		//display it
		var oldImage = '#img'+img_id;
		var newImage = 'img'+nextImage;
		$(oldImage).fadeTo('fast', 0, function(){
			$(this).attr('src', eval("image_"+nextImage+".src"));
			$(this).attr('alt', eval("image_"+nextImage+".alt"));
			$(this).attr('id', newImage);
			var time_id = setTimeout(function(){start_gallery($('#'+newImage))},1700);
			//log new showing pic
			var	timeouts = $("body").data('timeouts');
			stopSlideshows();
			timeouts.push(time_id);
			$("body").data('timeouts', timeouts);
			//$('#'+newImage).data('status', {'running' : true, 'id': time_id});
			$('#'+newImage).fadeTo('fast', 1);
		});		
	}
	else {
		//silently do nothing, this would indicate a bug of some sort
	}	
	return;
}

function get_gallery(id, link, section, display_link_to, gname){
	var json_data = new Object({
		'gid': id,
		'link_to' : link,
		'section' : section,
		'disp_link' : display_link_to,
		'gname' : gname
	});
	var element = "";
	$.ajax({ 
		url: "/gallery_handler.php",
        data: json_data,
        dataType: 'json',
        type: "POST",
        success: function( data ){
        	if (data['success'] == true){
				var gallery_name = '<div class="c_gallery_layer"><span>Gallery:</span><h1 class="c_gallery_layer">'+gname+'</h1></div>';
        		$("#the_holder").modal({
        			opacity: 70,
        			overlayClose: true,
        			onShow: function(){
        				$('#the_holder').galleria({
	         		    dataSource: data['data'],
	         	        width:800,
	         	        height:450,
	         	        showInfo:true,
	         	        _toggleInfo: false
						})
					}
        		});
				$(".galleria-info-text").prepend(gallery_name);
				$(".c_gallery_layer").fadeIn();
        	}
        }
	});
}
function confirmation(question, link) {
	var answer = confirm(question);
	if (answer){
		window.location.href = link;
	}
}
function validateEmail(email) { 
    var re = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
    return re.test(email);
} 
function check_rfq()
{
	var form=$("#rfq_form");
	var name = form.children("[name=name]");
	var email = form.children("[name=email]");
	var phone = form.children("[name=phone]");
	var company = form.children("[name=company]");
	var desc = form.children("[name=desc]");
	var refer = form.children("[name=refer]");
	
	if (name.val() == ""){
		alert("Please enter your name.");
		name.focus();
		return;
	}
	if (email.val() == ""){
		alert("Please enter your email.");
		email.focus();
		return;
	}
	if (validateEmail(email.val()) != true){
		alert("Please enter a valid email.");
		email.focus();
		return;
	}
	if (phone.val() == ""){
		alert("Please enter your phone number.");
		phone.focus();
		return;
	}
	if (company.val() == ""){
		alert("Please enter your company.");
		company.focus();
		return;
	}
	if (desc.val() == ""){
		alert("Please enter your project description.");
		desc.focus();
		return;
	}
	form.submit();
}
function check_contact()
{
	var form=$("#contact_form");
	var email = form.children("[name=email]");
	var desc = form.children("[name=desc]");

	if (email.val() == ""){
		alert("Please enter your email.");
		email.focus();
		return;
	}
	if (validateEmail(email.val()) != true){
		alert("Please enter a valid email.");
		email.focus();
		return;
	}
	if (desc.val() == ""){
		alert("Please enter your project description.");
		desc.focus();
		return;
	}
	form.submit();
}

function moveDown(element) {
	//check that one option is selected
	var options = element.siblings("select[name=gallery_select]").children();
	var select_count = element.siblings("select[name=gallery_select]").children("option:selected").length;
	var countOptions = options.length;
	if (select_count > 1){
		alert("Please only select one gallery at a time before changing its order.");
		return;
	}
	if (select_count == 0){
		alert("You must select a gallery before you can change its order.");
		return;
	}
	if (select_count == 1){
		var currIndex = options.filter(":selected").index();
		var nextPos = currIndex + 1;
		var sel_option_val = options.eq(currIndex).val();
		var sel_option_text = options.eq(currIndex).text();
		if (nextPos < countOptions){
			options.eq(nextPos).after("<option value='"+sel_option_val+"' selected='selected'>"+sel_option_text+"</option>");
			options.eq(currIndex).remove();
		}
	}
}
function moveUp(element) {
	//check that one option is selected
	var options = element.siblings("select[name=gallery_select]").children();
	var select_count = element.siblings("select[name=gallery_select]").children("option:selected").length;
	var countOptions = options.length;
	if (select_count > 1){
		alert("Please only select one gallery at a time before changing its order.");
		return;
	}
	if (select_count == 0){
		alert("You must select a gallery before you can change its order.");
		return;
	}
	if (select_count == 1){
		var currIndex = options.filter(":selected").index();
		var nextPos = currIndex - 1; //This is one of the main changes between move up and move down 
		var sel_option_val = options.eq(currIndex).val();
		var sel_option_text = options.eq(currIndex).text();
		if (nextPos >= 0){
			//changing after() to before() is the change here
			options.eq(nextPos).before("<option value='"+sel_option_val+"' selected='selected'>"+sel_option_text+"</option>");
			options.eq(currIndex).remove();
		}
	}
}
function submit_order(form_id){
	var order_array = new Array();
	var form = $("#"+form_id);
	form.children("select[name=gallery_select]").children().each(function(){
		order_array.push($(this).val());
	});
	var retstring = JSON.stringify(order_array);
	form.append("<input type='hidden' value='"+retstring+"' name='gallery_json'/>");
	form.submit();
}
function check_thumb_select(radio)
{
	//this function simply makes sure to select the picture that the radio belongs to be included in gallery slideshow
	var checkbox = radio.siblings("input[name='image[]']");
	if (!checkbox.is(":checked")){
		checkbox.attr("checked", "checked");
	}
}

