jQuery.noConflict();

var old_width;
var new_cord;
var corX;
var corY;

jQuery(document).ready(function() {

	Cufon.replace('h1.cufon',{textShadow: '0px 2px 0px #9a542f'});
	Cufon.replace('h2.cufon, .consultation h2', {color: '-linear-gradient(#ffffff, #fefefe, #f3f3f3, #e8e8e8)', textShadow: '0px 1px 0px #bd7c37'});
	Cufon.replace('h3.cufon',{color: '-linear-gradient(#f4dabf, #f3d3b2, #f3c59b, #f2bf8f)', textShadow: '0px 1px 0px #bd7c37'});

	Cufon.replace('.main-menu a',{hover: true, textShadow: '0px 1px 0px #ffffff'})('.map p')('#content.sub h4')('#content .categories-list ul li a',{ hover: true });
	Cufon.replace('.container .text-box p',{textShadow: '0px 2px 0px #9a542f'});
	Cufon.replace('.consultation h3',{color: '#f4dabf', textShadow: '0px 1px 0px #bd7c37'});

	jQuery('#footer ul li:last-child, .side-nav ul li:last-child').addClass('last');
	jQuery('.main-menu ul li:first-child').addClass('first');

	if( jQuery('.collapse').length > 0 ) {
		jQuery('.collapse').click(function() {
			if( jQuery('.additional-info').data('expanded') == 0 ) {
				jQuery('.additional-info').data('expanded', 1);
				jQuery('.additional-info').slideUp();
			} else {
				jQuery('.additional-info').data('expanded', 0);
				jQuery('.additional-info').slideDown(200);
			}
			return false;
		});
	}

	if( jQuery('.on-delete').length > 0 ) {
		jQuery('a.on-delete').click(function() {
			return window.confirm('You are trying to delete racquet. Please note, you will not be able to restore it. Click "OK" to continue or "Cancel" otherwise.');
		});
	}

	jQuery('a.toggle-link').click(function(){
		var targetid = jQuery(this).attr('rel');
		if(typeof(targetid) == undefined || !jQuery('#' + targetid).length){
			return false;
		}

		jQuery('#' + targetid).slideToggle('fast');
		return false;
	});

	jQuery('.wpsc_buy_button').click(function(){
		if(!jQuery('#product_grip_size').length){
			return;
		}

		if(jQuery('#product_grip_size').val() == ''){
			alert('Please, select grip size!');
			return false;
		}
	});

	if( jQuery('#carousel').length > 0 ) {
		jQuery('.ngg-gallery-thumbnail a').each(function(i, el) {
			jQuery('#carousel').append('<li><a href="' + jQuery(el).attr('href') + '"><img src="' + jQuery( jQuery(el).find('img').get(0) ).attr('src') + '" alt="" /></a></li>');
		});
	}

	if( jQuery('.ajax-form').length > 0 ) {
		jQuery('.ajax-form').submit(function() {
			jQuery('.error-msg').removeClass('complete-msg').hide();
			jQuery.post(jQuery('.ajax-form').attr('action'),  jQuery('.ajax-form').serialize(), function(data) {
				var answer = jQuery.parseJSON( data );

				if(answer.status == 'error') {
					jQuery('.error-msg').html(answer.message);
					jQuery('.error-msg').slideUp(300).delay(800).fadeIn(400, function() {
						jQuery(window).scrollTop(jQuery('.error-msg').position().top);
					});
				} else {
					if(answer.update_url != '') {
						window.location.href = answer.update_url;
					}
					jQuery('.error-msg').addClass('complete-msg').html(answer.message);
					jQuery('.error-msg').slideUp(300).delay(800).fadeIn(400);
				}
			});
			return false;
		});
	}

	if ( jQuery("#carousel").length ) {
		jQuery('#carousel').jcarousel({
			scroll: 3,
			wrap: 'both',
			initCallback: carouselCallback
		});
	}

	old_width = jQuery(document).width();
	window.onresize = function() {

		var window_w = jQuery(document).width();
		if (old_width > window_w){
			var xy = (old_width - window_w) / 2;
			new_cord = corX - xy;
		} else if (old_width < window_w){
			var xy = (window_w - old_width) / 2;
			new_cord = corX + xy;
		}
		old_width = window_w;
		corX = new_cord;
		jQuery('.lightbox').css('left', new_cord);
	};

	jQuery('.lightbox a.close, .overlay').click(function(){
		jQuery('.overlay').css('display', 'none');
		jQuery('.lightbox').css('display', 'none');
	});

	jQuery('.gallery-holder .ngg-gallery-thumbnail a').click(function() {
		jQuery('.lightbox .picture-area img').attr('src', jQuery(this).attr('href'));
		return false;
	});

	jQuery('.thumbs a').click(function() {
		jQuery('.lightbox .picture-area IMG').attr('src', jQuery(this).attr('href'));
		jQuery('.thumb-hover').css('display', 'none');
		/*jQuery('.left-shadow').css('display','none');*/
		/*jQuery(this).prepend('<div class="thumb-hover"><div>&nbsp;</div></div>');*/
		jQuery('.thumbs a').removeClass('active');
		jQuery(this).addClass('active');

		return false;
	});

	jQuery('.thumbs li:first a').click(function(){
		jQuery(this).parents('.thumbs').children('.left-shadow').css('display','block');
	});

	jQuery('.jcarousel-prev').click(function(){
		jQuery('.left-shadow').css('display','none');
	});

	jQuery('.jcarousel-next').click(function(){
		jQuery('.left-shadow').css('display','none');
	});

	jQuery('.pnd-popup form').submit(function() {
		if( jQuery('.pnd-popup form input[type="checkbox"]:checked').length == 3 ) {
			jQuery.post(jQuery(this).attr('action'), jQuery(this).serialize(), function( data ) {
				var answer = jQuery.parseJSON( data );
				if(answer.redirect != '') {
					window.location.href = answer.redirect;
				}
			});
		} else {
			jQuery('.pnd-popup, .popup-overlay').fadeTo(300, 0, function() {
				jQuery('.pnd-popup, .popup-overlay').hide();
			});
		}

		return false;
	});

	jQuery('.new-racket a').click(function() {
		jQuery('.submit-racket').toggle();
	});

	jQuery('.edit-pnd').click(function() {
		var img = jQuery(jQuery(this).find('img').get(0));
		img.attr('src', img.attr('src').replace('pencil.png', 'loader.gif'));

		jQuery.getJSON(jQuery(this).attr('href'), function(data) {
			img.attr('src', img.attr('src').replace('loader.gif', 'pencil.png'));

			jQuery('input[name="fullname"]').val(data.fullname);
			jQuery('input[name="phone"]').val(data.phone);
			jQuery('input[name="address_1"]').val(data.address_1);
			jQuery('input[name="address_2"]').val(data.address_2);
			jQuery('input[name="email"]').val(data.email);
			jQuery('input[name="date"]').val(data.pickup_ts);

			var found = false;
			jQuery('select[name="racket_name"] option').each(function(i, el) {
				if( jQuery(el).val() == data.make ) {
					jQuery(el).attr('selected', true);
					found = true;
					jQuery('#other-racket-name').hide();
				}
				if((i + 1) == jQuery('select[name="racket_name"] option').length && !found) {
					jQuery('select[name="racket_name"]').val('Other');
					jQuery('select[name="racket_name"]').parents('.row').fadeTo(1, 0.5).removeClass('required');
					jQuery('#other-racket-name input').val(data.make).removeClass('auto-hint');
					jQuery('#other-racket-name').show();
				}
			});

			jQuery('input[name="model"]').val(data.model);
			jQuery('textarea[name="comments"]').val(data.comments);
			jQuery('input[name="tension"]').val(data.tension);

			jQuery('select[name="options[grip_size]"]').val(data.grip_size);

			jQuery('select[name="options[string]"]').val(data.string);
			jQuery('select[name="options[string]"]').change();

			jQuery('select[name="options[main_string]"]').val(data.main_string);
			jQuery('select[name="options[cross_string]"]').val(data.cross_string);
			jQuery('input[name="options[main_tension]"]').val(data.main_tension);
			jQuery('input[name="options[cross_tension]"]').val(data.cross_tension);
			jQuery('select[name="options[overgrip]"]').val(data.overgrip);
			jQuery('select[name="options[replacement_grip]"]').val(data.replacement_grip);

			/*	OPTIONS	*/

			jQuery('input[name="pnd_id"]').remove();
			jQuery('.submit-racket .submit').append('<input type="hidden" name="pnd_id" value="' + data.id + '" />');
			jQuery('.new-racket a').remove();
			jQuery('.submit-racket').show();
		});
		return false;
	});

	if( jQuery('.custom-fields').length > 0 ) {
		//jQuery('.custom-fields select li').attr('selected', false);
		//jQuery('.custom-fields select > li').attr('selected', 'selected');

		if(jQuery('#custom_text').length > 0){
			jQuery('.custom-fields input').change(function(){
				updateHiddenProductDetails();
			});
		}

		jQuery('.custom-fields.product-addons select').change( function() {
			recalculatePrice( this );
		});

		//jQuery('select[name="options[string]"]').change();
		//jQuery(jQuery('.custom-fields select').get(0)).change();
	}

	if( jQuery('#select-string').length > 0 ) {
		var gut_blend_list = jQuery('#main-string').html();
		var syn_blend_list = jQuery('#cross-string').html();
	}

	jQuery('#select-string').change(function() {
		if( jQuery(this).find('option:selected').hasClass('hybrid') ) {
			var title = jQuery(this).find('option:selected').text().toLowerCase();

			if( title.indexOf('gut blend') != -1 ) {
				jQuery('#main-string, #cross-string').html(gut_blend_list);
			} else if(  title.indexOf('synthetic blend') != -1 ) {
				jQuery('#main-string, #cross-string').html(syn_blend_list);
			}
			jQuery('.string-hidden-fields').addClass('enabled').show();
			jQuery('input[name="tension"]').parents('.row').hide();
		} else {
			jQuery('.string-hidden-fields').removeClass('enabled').hide();
			jQuery('input[name="tension"]').parents('.row').show();
		}
	});

	jQuery('.reset').click(function() {
		window.location.href = window.location.href;

		return false;
	});

	jQuery('.view-popup').click(function() {

		jQuery('.view-order-details-popup .item-details').html('<div class="loading"></div>');
		jQuery('.view-order-details-popup .item-details').load(jQuery(this).attr('href'));

		jQuery('.view-order-details-popup, .popup-overlay').fadeTo(1, 0, function() {
			jQuery('.view-order-details-popup, .popup-overlay').show();
			jQuery('.view-order-details-popup, .popup-overlay').fadeTo(100, 1);
		});
		return false;
	});

	jQuery('.view-order-details-popup .close').click(function() {
		jQuery('.view-order-details-popup, .popup-overlay').fadeTo(200, 0, function() {
			jQuery('.view-order-details-popup, .popup-overlay').hide();
		});
		return false;
	});

	var today = new Date();
	var max_date = new Date ( today );
	max_date.setTime(today.getTime() + 5184000000); // 60 * 60 * 24 * 60 * 1000 = 5184000000 = number of microseconds in two monthes

	jQuery('#date').datepicker({
		minDate: today,
		maxDate: max_date,
		dateFormat: 'm/d/yy',
		dayNamesMin: ['Su','Mo','Tuesday','We','Thursday','Fr','Sa'],
		constrainInput: true,
		beforeShowDay: restrictedDays
	});

	jQuery('#wpsc_shopping_cart_container').submit(function() {
		if( jQuery('input[value="wpsc_merchant_paypal_pro"]:checked').length > 0 ) {
			if( jQuery('input[name="card_number"]').val() == '' ) {
				if( jQuery('.login_error').length == 0 ) {
					jQuery(this).find('form').prepend('<div class="login_error"></div>');
				}
				jQuery('.login_error').html('<p class="validation-error">Please, supply your credit card number.</p>');

				return false;
			}
			if( jQuery('input[name="card_code"]').val() == '' ) {
				if( jQuery('.login_error').length == 0 ) {
					jQuery(this).find('form').appendBefore('<div class="login_error"></div>');
				}
				jQuery('.login_error').html('<p class="validation-error">Please, supply your credit card code (CVV).</p>');

				return false;
			}
		}
	});

	if( jQuery('select[name="racket_name"]').length > 0 ) {
		jQuery('select[name="racket_name"]').change(function() {
			if( jQuery(this).val() == 'Other' ) {
				jQuery('#other-racket-name').slideDown(300);
				jQuery(this).parents('.row').fadeTo(100, 0.5).removeClass('required');
			} else {
				jQuery('#other-racket-name').slideUp(100);
				jQuery(this).parents('.row').fadeTo(100, 1).addClass('required');
			}
		});
	}

	jQuery('.auto-hint').focus(function() {
		if( jQuery(this).val() == jQuery(this).attr('title') ) {
			jQuery(this).val('');
		}
		jQuery(this).removeClass('auto-hint');
	});

	jQuery('.auto-hint').blur(function() {
		if( jQuery(this).val() == '' ) {
			jQuery(this).val(jQuery(this).attr('title'));
			jQuery(this).addClass('auto-hint');
		}
	});
});

function recalculatePrice( obj ) {
	var base_price = parseFloat(jQuery('input[name="base_price"]').val());
	var grand_addon_price = 0;

	jQuery('.custom-fields.product-addons select').each(function( i, el ) {
		var elid = jQuery(el).attr('id');
		if(elid == 'main-string' || elid == 'cross-string'){
			return;
		}

		if( ( jQuery(el).parents('.string-hidden-fields').length > 0 && jQuery(jQuery('select[name="options[string]"] option').get(jQuery('select[name="options[string]"]').attr('selectedIndex'))).hasClass('hybrid') ) || jQuery(el).parents('.string-hidden-fields').length == 0 ) {
			var addon_price = parseFloat( jQuery(jQuery(el).find('option').get(el.selectedIndex)).attr('title') );
			// console.log(el);
			// console.log(addon_price);
			base_price += addon_price;
			grand_addon_price += addon_price;
			jQuery('strong.show-price').text( base_price.toFixed(2) );
		}
	});

	if(jQuery('#donation_price').length > 0){
		jQuery('#donation_price').val(base_price);
	}

	updateHiddenProductDetails();
}

function updateHiddenProductDetails()
{
	// Set product info details
	if(jQuery('#custom_text').length > 0){

		var details = '';
		jQuery('.custom-fields select, .custom-fields input').each(function(){
			if(jQuery(this).is(':visible')){
				var val = jQuery(this).val();
				if(jQuery(this).get(0).tagName == 'SELECT'){
					val = jQuery(this).children(':selected').text();
				}

				if(val == ''){
					val = '- Not Set -';
				}

				details += jQuery(this).attr('title') + ": " + val + "\r\n";
			}
		});

		jQuery('#custom_text').text(details);
	}
}

function hideCartForm( pnd_info ) {
	var data = jQuery.parseJSON( pnd_info );

	jQuery('input[title="billingemail"]').val( data.email );
	jQuery('input[title="billingfirstname"]').val( data.firstname );
	jQuery('input[title="billinglastname"]').val( data.lastname );
	jQuery('textarea[title="billingaddress"]').val( data.address );
	jQuery('input[title="billingcity"]').val( 'New York' );
	jQuery('input[title="billingpostcode"]').val('');
	jQuery('input[title="billingphone"]').val( data.phone );

	jQuery('select[title="billingstate"] option').each(function(i, el) {
		if(jQuery(el).text() == 'New York') {
			jQuery(el).attr('selected', true);
		}
	});
	jQuery('input[title="billingcountry"]').val('US');

	jQuery('.wpsc_billing_forms').parents('tr').hide();

	jQuery('form.wpsc_checkout_forms td').each(function(i, el) {
		if(jQuery(el).attr('class').toLowerCase().substr(0, 19) == 'wpsc_checkout_form_') {
			jQuery(el).parents('tr').hide();
		}
	});
}

function restrictedDays(date) {
	var day = date.getDay();
	return [( day == 2 || day == 4 )];
}


function carouselCallback( carousel ) {
	jQuery('.gallery-holder .ngg-gallery-thumbnail a').click(function() {
		var h = jQuery(document).height();
		var x = jQuery(document).width();
		var coord = jQuery(this).offset();
		var scroll = jQuery(window).scrollLeft();
		var corZ = jQuery(window).width();
		var corC = jQuery('.lightbox').width();
		corX = ( (corZ - corC) / 2 );

		jQuery('#carousel a').removeClass('active');
		jQuery('#carousel a[href="' + jQuery(this).attr('href') + '"]').addClass('active');

		jQuery('.overlay').css('height', h + 'px').css('display', 'block');
		jQuery('.overlay-bg').css('height', h + 'px').css('display', 'block');

		jQuery('.lightbox').css({'marginTop': ( jQuery(window).height() - jQuery('.lightbox').height() ) / 2 + 'px', 'left':( jQuery(window).width() - jQuery('.lightbox').width() ) / 2 + 'px'});

		jQuery('.lightbox').css('display', 'block');
		jQuery('.thumbs').insertAfter('.picture-area').css( {position: 'relative', visibility: 'visible'} );

		carousel.scroll( jQuery('#carousel a').index( jQuery('#carousel a[href="' + jQuery(this).attr('href') + '"]') ) );

		return false;
	});
}

function initForm() {
	jQuery('.repay-form').submit(function() {
		jQuery.post(jQuery(this).attr('action'), jQuery(this).serialize(), function( data ) {
			var answer = jQuery.parseJSON( data );
			if(answer != null && answer.redirect != '') {
				window.location.href = answer.redirect;
			} else {
				alert('Service temporarily unavailable, please try again later.');
			}
		});

		return false;
	});
}

function rbApplyNewBasePrice(price) {
	jQuery('input[name="base_price"]').val(price);
	jQuery('.currentprice.pricedisplay').html('$<strong class="show-price">' + price + '</strong>');
	recalculatePrice( null );
};

