//******************
//TOGGLE DIV DISPLAY
//******************
function toggleBlind(div1, div2) {

	if (div2 === undefined) {

		if ($(div1).hasClassName('open')) {
			Effect.BlindUp(div1, { duration: 0.25 });
			$(div1).removeClassName('open');
		} else {
			Effect.BlindDown(div1, { duration: 0.25 });
			$(div1).addClassName('open');
		}

	} else {

		if (!$(div1).hasClassName('open')) {
			Effect.BlindUp(div2, { duration: 0.25 });
			$(div2).removeClassName('open');
			Effect.BlindDown(div1, { duration: 0.25, delay: 0.35 });
			$(div1).addClassName('open');
		}

	}

}

function toggleBlindAll(direction, divs) {

	var len = divs.length;
	for (var i = 0; i < len; i++) {

		if (direction == "up") {
			Effect.BlindUp(divs[i], { duration: 0.25 });
			$(divs[i]).removeClassName('open');
		} else if (direction == "down") {
			Effect.BlindDown(divs[i], { duration: 1 });
			$(divs[i]).addClassName('open');
		}

	}

}

function deleteItem(team, type, id) {
	var msg = "Are you sure you want to delete this " + type + "?";
	if (confirm(msg)){
		location.replace("?t=" + team + "&action=delete&id=" + id);
	}
}

function flagItem(comment_id, query_string) {
	var msg = "Are you sure you want to report this comment?";
	if (confirm(msg)){
		location.replace(query_string);
	}
}

function clearField(form_name, field_name) {

	if (document.forms[form_name].elements[field_name].value == "Add a comment...") {
		document.forms[form_name].elements[field_name].value = "";
	}

}

/* AJAX
------- */
function processForgotPassword(email) {
	
	var dataString = ({'email': email});

	$.ajax({
		url: "/objects/ajax/process_forgot_password.php",
		data: dataString,
		type: "GET",
		success: function(response) {
			$("div#forgotPasswordOverlayText").html(response);
		},
		error: function(xhr, err, e) {
			alert("Forgot password error: " + err);
		}
	});
	
}
	
function processValidationEmail(email) {
	
	var dataString = ({'email': email});

	$.ajax({
		url: "/objects/ajax/process_validation_email.php",
		data: dataString,
		type: "GET",
		success: function(response) {
			$("div#forgotPasswordOverlayText").html(response);
		},
		error: function(xhr, err, e) {
			alert("Validation e-mail error: " + err);
		}
	});
	
}

/* Fancy Thumbnail Hover Effect w/ jQuery
http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/#blog
----------------------------------------- */
$(document).ready(function() {

    $(".product .photo img").hover(function() {
		
		var image_id = $(this).attr('id').split('|');
		var small_image_width = image_id[0];
		var small_image_height = image_id[1];
		var big_image_width = Math.round(small_image_width * 2);
		var big_image_height = Math.round(small_image_height * 2);

		$(this).parent().css({
			'z-index': '10'
		});

		$(this).css({
			'z-index': '10'
		});

		$(this).addClass("hover").stop().animate({
			marginLeft: '-' + Math.round(big_image_width / 2) + 'px',
			marginTop: '-' + Math.round(big_image_height / 2) + 'px',
			top: '50%',
			width: big_image_width + 'px',
			height: big_image_height + 'px'
		}, 200);

	}, function() {

		var image_id = $(this).attr('id').split('|');
		var small_image_width = image_id[0];
		var small_image_height = image_id[1];
		
		$(this).parent().css({
			'z-index': '0'
		});

		$(this).css({
			'z-index': '0'
		});

		$(this).removeClass("hover").stop().animate({
			marginLeft: '-' + Math.round(small_image_width / 2) + 'px',
			marginTop: '0',
			top: '0',
			width: small_image_width + 'px',
			height: small_image_height + 'px'
		}, 400);

	});

});

/* OVERLAYS
----------- */
/*
 * jQuery UI fade effect, based on pulsate
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *      effects.core.js
 */
/*
 * jQuery UI fade effect, based on pulsate
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *      effects.core.js
 */
(function($) {

    $.effects.fade = function(o) {

        return this.queue(function() {

            // Create element
            var el = $(this);

            // Set options
            var speed = o.options.speed || 500;
            var mode = o.options.mode || 'show'; // Set Mode

            // Animate
            if (mode == 'show') {
                el.fadeIn(speed);
            } else {
                el.fadeOut(speed);
            }
            ;
            el.queue('fx', function() {
                el.dequeue();
            });
            el.dequeue();
        });
    };

})(jQuery);
        
function overlay(divId) {
    $('.dialog').dialog('destroy');
    $('#' + divId).dialog({
        autoOpen: false,
        dialogClass: 'overlay',
        draggable: false,
        hide: 'fade',
        modal: true,
        resizable: false,
        show: 'fade',
        width: 286
    });
    $('#' + divId).dialog('open');
}

function overlayClose(divId) {
    $('#' + divId).dialog('close');
}

// GENERIC CODE TO SHOW AND HIDE ERRORS
function showError(fieldRow, message) {
    $('#' + fieldRow + 'Row .formError').html(message);
    if (!$('#' + fieldRow + 'Row').hasClass('error')) {
        $('#' + fieldRow + 'Row').addClass('error');
        $('#' + fieldRow + 'Row .formError').slideDown();
    }
}

function hideError(fieldRow) {
    $('#' + fieldRow + 'Row').removeClass('error');
    $('#' + fieldRow + 'Row .formLabel').removeClass('error');
    $('#' + fieldRow + 'Row .formError').slideUp().html('');
}

// VALIDATION
function validateFirstName(fieldRow, name, required) {
	
	if (required && name == "") {
		showError(fieldRow, 'Please enter a first name.');
        return false;
    } else {
        hideError(fieldRow);
        return true;
    }		
		
}

function validateLastName(fieldRow, name, required) {
	
	if (required && name == "") {
		showError(fieldRow, 'Please enter a last name.');
        return false;
    } else {
        hideError(fieldRow);
        return true;
    }		
		
}

function validatePhone(fieldRow, phone, required) {
	
	if (required && phone == "") {
		showError(fieldRow, 'Please enter a phone number.');
        return false;
    } else {
        hideError(fieldRow);
        return true;
    }		
		
}

function validateEmail(fieldRow, email, required) {
	
    var regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    //make sure an email address has been entered
	if (required && email == "") {
		showError(fieldRow, 'Please enter an e-mail address.');
        return false;
		
    //check that email is in the correct format and doesn't have any invalid characters
    } else if (!regExp.test(email)) {
		showError(fieldRow, 'Invalid e-mail address.');
        return false;
		
    } else {
        hideError(fieldRow);
        return true;
    }		
		
}

function validateMessage(fieldRow, message, required) {
	
	if (required && message == "") {
		showError(fieldRow, 'Please enter a message.');
        return false;
    } else {
        hideError(fieldRow);
        return true;
    }		
		
}

jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		attribute: "maxlength",
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = parseInt(textarea.attr(settings.attribute));

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}

//code to execute after the DOM has finished loading
$().ready(function() {

    //add default text field and drop-down highlighting for all forms
    $('.formField input:text, .formField input:password, .formField select, .formField textarea').bind('focus blur', function() {
        $(this).toggleClass('focus');
    });

	//trim whitespace from all form values
	$('.formField input:text, .formField input:password, .formField textarea').bind('blur', function() {
		$(this).val($.trim($(this).val()));
	});
	
	$('.formField input#first_name').bind('blur', function() {
		validateFirstName('firstName', $(this).val(), true);
	});

	$('.formField input#last_name').bind('blur', function() {
		validateLastName('lastName', $(this).val(), true);
	});

	$('.formField input#phone').bind('blur', function() {
		validatePhone('phone', $(this).val(), false);
	});

	$('.formField input#email').bind('blur', function() {
		validateEmail('email', $(this).val(), true);
	});

	$('.formField textarea#message').bind('blur', function() {
		validateMessage('message', $(this).val(), true);
	});

	$('form#contact a#submit').bind('click', function() {
		
		validateFirstName('firstName', $('.formField input#first_name').val(), true);
		validateLastName('lastName', $('.formField input#last_name').val(), true);
		validatePhone('phone', $('.formField input#phone').val(), false);
		validateEmail('email', $('.formField input#email').val(), true);
		validateMessage('message', $('.formField textarea#message').val(), true);
	
		if (
			(!$('#firstNameRow').hasClass('error')) &&
			(!$('#lastNameRow').hasClass('error')) &&
			(!$('#phoneRow').hasClass('error')) &&
			(!$('#emailRow').hasClass('error')) &&
			(!$('#messageRow').hasClass('error'))
		) {
			$('form#contact').submit();
		} else {
			scrollWindow('formTop');	
		}
		
		return false;
		
	});

	var onEditCallback = function(remaining){
		$(this).siblings('.charsRemaining').text("Characters remaining: " + remaining);

		if(remaining > 0){
			$(this).css('background-color', '#ffffff');
		}
	}

	var onLimitCallback = function(){
		$(this).css('background-color', '#ffcccc');
	}

	$('textarea[maxlength]').limitMaxlength({
		onEdit: onEditCallback,
		onLimit: onLimitCallback
	});
	
	//create rotating testimonials on home page
	$('div#testimonials').cycle({
		fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
		speed: 1000,
		timeout: 5000
	});

	
});

