//Initializes several functions
$(document).ready( function() {
	thru = 0;
	$('.quote').hide();
	roTate(thru);
    //gAllery();
	
		newGallery();
	
});


function newGallery() {
	if( !$('#galleryWrap').size() ) return false;
	
	var obj = $('#galleryWrap');
	var lightBox =	'<div id="lightBox">\
						<img />\
						<div class="caption"></div>\
					</div>'
	var shade = '<div id="shade"></div>'

	$(shade).css({
		'position': 'absolute',
		'z-index': '100',
		'width': '100%',
		'height': $('#mWrap').outerHeight() + 100,
		'top': '0px',
		'left': '0px',
		'background-color': 'black',
		'opacity': '0.7',
		'display': 'none'
	}).appendTo( $('body') );
	
	$(lightBox).css({
		'position': 'absolute',
		'z-index': '200',
		'width': 'auto',
		'height': 'auto',
		'display': 'none',
		'background-color': 'white',
		'padding': '5px',
		'cursor': 'pointer',
		'-moz-box-shadow': '3px 3px 3px #000',
		'-webkit-box-shadow': '3px 3px 3px #000',
		'box-shadow': '3px 3px 3px #000'
	}).appendTo( $('body') );

	$('#lightBox').click( function(){
		$('#shade').toggle('medium');
		$('#lightBox').toggle('fast');
	});
	
	$('#lightBox').find('img:eq(0)').css({
		'height': '500px',
		'width': 'auto'
	});
	
	$('#lightBox').find('.caption').css({
		'text-align': 'center',
		'font-family': 'Times New Roman, Serif',
		'font-size' : '11pt',
		'color': '#eee',
		'padding': '3px',
		'background-color': '#555',
		'margin-top': '5px'
	});
	
	obj.find('a').each( function(){
		$(this).css({
			'width': '150px',
			'height': '150px',
			'position': 'relative',
			'float': 'left',
			'margin': '10px 10px 20px 10px',
		});
		
		$(this).find('img').each( function(){
			$(this).css({
				'width': '150px',
				'height': 'auto',
				'border': 'solid white 2px'
			});
		});
		
		$(this).bind('click', function(e){
			var href = $(this).attr('href');
			var alt = $(this).find('img:eq(0)').attr('alt');

			$('#lightBox').find('img:eq(0)').attr('src', href);
			$('#lightBox').find('div.caption').text( alt );
			$('#shade').toggle('fast');
			$('#lightBox').toggle('medium', function(){
				var h = $(this).find('img:eq(0)').height();
				var w = $(this).find('img:eq(0)').width();
				var winH = $(window).height();
				var winW =  $(window).width();

				$(this).css({
					'left': (winW - w) / 2,
					'top': (winH - h) / 2
				});
			});
			return false;
		});
		
	});
	
}




//Controls the rotating of the quotes
function roTate(thru) {
	var nOf = $('.quote').size()-1;
	if(thru > nOf) thru = 0;
	$('.quote:eq(' + thru + ')').fadeIn('slow').delay(10000).fadeOut('slow', function() {
		roTate(thru+1);
	});
}


//Sets up the gallery to handle the next/prev buttons
function gAllery() {
    if( !$('#galWrap').size() ) return false;

    enAbler();
    var wWidth = $('#galWrap').find('.pic').size();


    $('#pics').css('width', wWidth*600);
    $('#next').click( function() {
        var pPos = $('#pics').position();
        if(pPos.left-600 <= -1*(wWidth*600)) return false;
        $('#pics').animate({'left' : pPos.left - 600 }, function() { enAbler() } );
    });
    $('#prev').click( function() {
        var pPos = $('#pics').position();
        if(pPos.left == 0) return false;
        $('#pics').animate({'left' : pPos.left + 600 }, function() { enAbler() } );
    });
}


//Resizes the images in the gallery if they're too large for the available space. Had to attach this via window.onload because
//it's the only reliable way to know if an image is truly loaded. jQuery is often fooled by cached images.
window.onload = function() {
/*
    var imgArray = [];
    $('#pics').find('.anImg').each( function(index) {
            imgArray[index] = new Image;
            imgArray[index].src = $(this).attr('src');
    
            var w = imgArray[index].width;
            var h = imgArray[index].height;
    
            while( w > 400 || h > 300) {
                w = Math.round(w * 0.9);
                h = Math.round(h * 0.9);
            }
    
            var mArgin = Math.round( (300 - h) / 2 );
            $(this).css({ 'height' : h , 'width' : w, 'margin' : '0px ' + mArgin + 'px' });

            $(this).next().css({'width' : w+4, 'margin' : '0px auto' });
    });
	*/
}


//Makes the available area for the gallery the right width, and sets whether or not the next/prev arrows are visible
function enAbler() {
    var pPos = $('#pics').position();
    var wWidth = ($('#galWrap').find('.pic').size()-1) * 600 * -1;

    if(pPos.left == 0) {
        if($('#next:hidden')) $('#next').fadeIn('fast');
        else $('#next').css('color', 'white');
        $('#prev').fadeOut('fast');
    }
    else if ( pPos.left == wWidth ) {
        if($('#prev:hidden')) $('#prev').fadeIn('fast');
        else $('#prev').css('color','white');
        $('#next').fadeOut('fast');
    }
    else {
        if($('#next:hidden')) $('#next').fadeIn('fast');
        else $('#next').css('color', 'white');

        if($('#prev:hidden')) $('#prev').fadeIn('fast');
        else $('#prev').css('color','white');
    }
}


//########################################################################################################################################
// ORDER FORM STYLES
//########################################################################################################################################
var TOTAL=[$('#orderForm').find('input:text, select, input:radio').size()];
$( function() {
	if( $('#orderForm').size()==0 ) return false;
	$('#orderForm').get(0).reset();
	$('.helpBox, .sEcond').hide();
	$('.addTwo').moreOrder('sEcond');
	$('#silhouette-type').initType('#silhouette-type_formId');
	$('#2-silhouette-type').initType('#2-silhouette-type_formId');
	//$('#extra-matted-copies_formId, #oval-frames').copiesFrames('#extra-matted-copies_formId', '#oval-frames');
	//$('#2-extra-matted-copies_formId, #2-oval-frames').copiesFrames('#2-extra-matted-copies_formId', '#2-oval-frames');
	$('#extra-matted-copies_formId, #2-extra-matted-copies_formId').copiesFrames(7);
	$('#oval-frames_formId').copiesFrames(10);
	
	$('.help').showHelp();
	$('.forwardButton').sUbmit();
});

//Displays the second order, or hides it
$.fn.moreOrder = function(obj) {
	this.click( function() {
		$('.' + obj).each( function(){
			if( $(this).is(':visible') )
				$(this).fadeOut('medium', function(){
					cAlculate('no','no');
				});
			else if( !$(this).hasClass('hide') )
				$(this).fadeIn('medium', function(){
					cAlculate('no','no');
	
			});		
		});	
	});
};

//Attaches the necessary functionality for the Silhouette Type dropdown
$.fn.initType = function(obj) {
	this.bind('click change', function() {
		if( $(this).is(':visible') ) {
			var vAlue = parseFloat( /\[\$(.*?)\]/.exec( $(this).val() )[1] );
			cAlculate(vAlue, getIndex(this));
			$(obj).val( $(this).val() );
			//alert( $(obj).val() );
		}
		var vAlue = $(this).attr('selectedIndex') - 1;
		var startPoint = $(this).closest("tr");
		switch(vAlue) {
			case 1: startPoint.prev().prev().fadeOut('fast');
					startPoint.prev().fadeOut('fast'); break;
			case 2: startPoint.prev().prev().fadeIn('fast');
					startPoint.prev().fadeOut('fast'); break;			
			case 3: startPoint.prev().prev().fadeIn('fast');
					startPoint.prev().fadeIn('fast'); break;					
		}
		
	});
}

//Attaches functionality for the Copies dropdown and the Frames checkbox
$.fn.copiesFrames = function(pRice) {
	this.bind('change click', function(){
		var cOpies = parseInt( $(this).val() ) * pRice;
		cAlculate( cOpies, getIndex( $(this) ) );	
	});
};


//Gets the index of the form element within the form field range to basically assign a unique position to each value, so there are no duplicates
function getIndex(obj) {
	return index = $('#orderForm').find('input:text, select, input:checkbox').index( $(obj) );
}

//Calculates shipping and handling
function sHipping() {
	var sh=0;
	var shTotal=0;
	var count=1;
	
	$('.sh').each( function(){
		if( $(this).is(':visible') ) {
			sh += parseInt( $(this).val() );
			//count++;
		}
	});
	
	sh+=count;
	
	for(i=0;i<sh;i++) {
		if( i<=2 ) shTotal+=3;
		else shTotal+=2;
	}	
	
	return shTotal;
}

//Adds up the form values and outputs them
function cAlculate(vAlue, index) {
	var sh = sHipping(
);
	if(vAlue!='no') TOTAL[index] = vAlue;
	field = 0;
	
	for(i=0;i<TOTAL.length;i++) {
		tmpy = $('#orderForm').find('input:text, select, input:checkbox').eq(i).is(':visible');
		
		if( typeof TOTAL[i] == 'number' && tmpy ) {
			field+= TOTAL[i];
			
		}
	}
	
	tOtal = parseInt(sh) + parseInt(field);
	
	$('#sh').text( '$' + sh.toFixed(2) );
	$('#cost').text( '$' + field.toFixed(2) );
	$('#total_formId').val( '$' + tOtal.toFixed(2) );
	$('#total').text( '$' + tOtal.toFixed(2) );
}

//Shows the help boxes when clicked
$.fn.showHelp = function() {
	this.click( function(){
		$(this).closest('tr').next().find('.helpBox:eq(0)').toggle('fast');
		return false;
	});
};

//Applies the errCheck function to required fields and does the final check to see if the form is filled out correctly
$.fn.sUbmit = function() {
	this.click( function() {
		cAlculate('no','no');
		var proceed = 0;
		
		$('input').each( function(){
			if( $(this).attr('type') == 'text' && $(this).is(':visible') )
				proceed += $(this).errCheck('');
			if( $(this).attr('type') == 'file' && $(this).is(':visible') )
				proceed += $(this).errCheck('file');
		});
		proceed += $('#state_formId').errCheck('Select a State');
		proceed += $('#silhouette-type').errCheck('Please Select');
		if(	$('#2-silhouette-type').is(':visible') )
			proceed += $('#2-silhouette-type').errCheck('Please Select');
		
		if(proceed==0)
			$('#orderForm').get(0).submit();
		else
			alert(' You have left '+ proceed +' necessary fields blank. Please enter them and resubmit.');
	});
};

//Checks to see if a passed field is blank or not
$.fn.errCheck = function(cOmpare) {
	var lAbel = this.parent().prev();
	var fLabel = this.parentsUntil('.data').parent().prev();
	
	if(cOmpare == 'file' && this.val().length <= 1){
		this.parentsUntil('.data').parent().prev().css('color', 'red');
		return 1;
	}
	else if( this.val() == cOmpare ) {
		lAbel.css('color', 'red');return 1;
	}
	else {
		lAbel.css('color', 'black');
		fLabel.css('color', 'black');return 0;
	}
};
//########################################################################################################################################
// END ORDER FORM STYLES
//########################################################################################################################################



//Supersleight script for making png's transparent in IE 6.
//Created by Drew McLellan
jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: '/uploads/98/cc/98cc5314f9d8c3004f7811cdedc33cdc/x.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
					self.css('position', 'relative');
				};
			});
		};
	});
};

$( function(){
	$('#header').supersleight();		
});




