/* Javascript Document Copyright 2006-2009 Andrei Gonzales. All Rights Reserved */
/* Version 1.0 */
/* Type: Javascript General Code Sheet for Big Richard Clothing Main Website */

$(document).ready(function(){
/***************************************
*** Common Misc JavaScript Functions ***
***************************************/
// Adjust CSS for confirmation page
if ($('#confirmpage').hasClass('yessir')){
	$('#scroller').css('display','none');	
}

// Replace Submit buttons with anchors and Validate Forms
$('.jquerybtn').each(function(){		
	$(this).parents('form.cmxform').validate({
		highlight: function(element){
			$(element).addClass("errbar");
		},
		unhighlight: function(element){
			$(element).removeClass("errbar");
		},
		errorPlacement: function(error, element){
			error.appendTo(element.next(".errorbox"));
		}
	});
	// Above error function is necessary for the last line below to work
	var formId = $(this).parents('form.cmxform').attr('id');
	var elId = $(this).attr('id');
	var elName = $(this).attr('name');
	var elClass = $(this).attr('class');
	var elTitle = $(this).attr('title');
	var tIndex = $(this).attr('tabindex');
	var nuText = $(this).val();
	$(this).after('<a id="'+elId+'1" tabindex="'+tIndex+'" name="'+elName+'1" class="'+elClass+'" title="'+elTitle+'" onclick="$(\'#'+formId+'\').trigger(\'submit\');">'+nuText+'</a>').remove();
});

$('.jquerysub').each(function(){		
	$(this).parents('form.cmxform').validate({
		highlight: function(element){
			$(element).addClass("errbar");
		},
		unhighlight: function(element){
			$(element).removeClass("errbar");
		},
		errorPlacement: function(error, element){
			error.appendTo(element.next(".errorbox"));
		}
	});
	// Above error function is necessary for the last line below to work
	var formId = $(this).parents('form.cmxform').attr('id');
	var elId = $(this).attr('id');
	var elName = $(this).attr('name');
	var elClass = $(this).attr('class');
	var elTitle = $(this).attr('title');
	var tIndex = $(this).attr('tabindex');
	var nuText = $(this).val();
	$(this).after('<a id="'+elId+'1" tabindex="'+tIndex+'" name="'+elName+'1" class="'+elClass+'" title="'+elTitle+'" onclick="$(\'#'+formId+'\').trigger(\'submit\');">'+nuText+'</a>').remove();
});

$('.addtocart').each(function(){		
	$(this).parents('form.cmxform').validate({
		highlight: function(element){
			$(element).addClass("errbar");
		},
		unhighlight: function(element){
			$(element).removeClass("errbar");
		},
		errorPlacement: function(error, element){
			error.appendTo(element.next(".errorbox"));
		}
	});
	// Above error function is necessary for the last line below to work
	var formId = $(this).parents('form.cmxform').attr('id');
	var elId = $(this).attr('id');
	var elName = $(this).attr('name');
	var elClass = $(this).attr('class');
	var elTitle = $(this).attr('title');
	var tIndex = $(this).attr('tabindex');
	var nuText = $(this).val();
	$(this).after('<a id="'+elId+'1" tabindex="'+tIndex+'" name="'+elName+'1" class="'+elClass+'" title="'+elTitle+'" onclick="$(\'#'+formId+'\').trigger(\'submit\');">'+nuText+'</a>').remove();
});

/*** Feedback Page Radio Button ***/
$('#participatechoicen').click(function(){
	$('#participateemail').removeClass('required').removeClass('email');
});

$('#participatechoicey').click(function(){
	if($('#participateemail').hasClass('email')){return;}else{$('#participateemail').addClass('required').addClass('email');}
});
	
/*** Input Field - clearing default values ***/
var default_values = {};
	jQuery('input, textarea').each(function(i) {
    var index = jQuery(this).attr('name');
    var value = jQuery(this).val();
    default_values[index] = value;
  	});

  	jQuery('input, textarea').focus(function() {
    if(jQuery(this).val() === default_values[jQuery(this).attr('name')]) {
      jQuery(this).val('');
    }
});

/*** Product Page -> Replace Drop Down with buttons **/
var storeops = "";										// Create empty container for stored elements
var target = $('.variations').find('select');			// find drop downs within the variations element
var choices = target.find('option[value!=""]');			// find all option choices that have a value
var mainl = target.prev('label');						
choices.each(function(){	
	var content = $(this).text();						// copy the text/innerhtml inside each of the option elements
	var nameval = $(this).val();						// copy the value of each option element
	var newops = '<a href="" class="prodops" name="'+nameval+'">'+ content + '</a>'; // wrap each text and value within new html elements
	storeops += newops;									// add each newly wrapped element into the storeops container
});

mainl.after('<span class="newops">'+storeops+'</span>');// insert contents of storeops container after the original element's label
target.addClass('hiddenops');							// hide original element

$('.prodops').toggle(
	function(){ 										// Select a size
		$(this).prevAll('a').removeClass('chosen'); 	// Clear out previously selected choices 
		$(this).nextAll('a').removeClass('chosen'); 	//
		$(this).addClass('chosen');						// Maintain selected state
		var equiv = $(this).attr('name');
		choices.each(function(){
			if($(this).val()==equiv){					// Find equivalent target in option choices
				$(this).attr('selected','selected');	// Select equivalent option
			} else {
				return;
			}
		});
	},
	function(){
		$(this).removeClass('chosen');
		var equiv = $(this).attr('name');
		choices.each(function(){
			if($(this).val()==equiv){
				$(this).removeAttr('selected');
			} else {
				return;
			}
		});
	}
);

/*** Image Gallery Carousel on Product Pages ***/
// Create New elements for Carousel
$('.thumbnails').wrap('<div class="thumbnailset"></div>');
$('.thumbnails').before('<span class="navshelf"><a class="gallerynav up">up</a></span>');
$('.thumbnails').after('<span class="navshelf"><a class="gallerynav down">down</a></span>');

// Infinite Image Carousel
$('.up').click(function(){
	var firstbit = $('.thumbnails').find('li:first');
	firstbit.clone().appendTo('.thumbnails').stop();
	firstbit.slideUp(2000);
	firstbit.remove();
});

$('.down').click(function(){
	var lastbit = $('.thumbnails').find('li:last');
	lastbit.clone().prependTo('.thumbnails').stop();
	lastbit.slideDown(2000);
	lastbit.remove();
});

// View Larger Image Replacement Script
$('.thumbnails > li > img').livequery(function(){
	$(this).click(function(){
		var trigger = $(this).parent('li').attr('rel');
		var target = $('.previews').find('li[id="'+trigger+'"]');
			target.prevAll().removeClass('active').animate({opacity: 0.0},1000);
			target.nextAll().removeClass('active').animate({opacity: 0.0},1000);
			target.animate({opacity: 1.0},1000).addClass('active');
		});
	});
	

/** Product Scroller **/



/*** IE6 Stuff ***/
$('#ie6warning').click(function(){$(this).css('display','none');});


/*** Custom Scroll Bar ***/

  if($.browser.opera){
  	// do nothing
  }else{
  	$('.scrollpane').jScrollPane({scrollbarWidth:5});
  }

  if($.browser.msie && jQuery.browser.version == 6){
  	// do nothing
  }else{
  	$('.scrollpane').jScrollPane({scrollbarWidth:5});
  }


/* Fixed Page Scrolling */

/* For Products */

var gallery = jQuery('body.half-width #product-page .gallery .previews');
if(gallery.length > 0){
  //gallery.after('<div class="click-to-enlarge">Click to Enlarge</div>');
}


//calaculate total product width
if(jQuery('body.fixed-width').length > 0){
  var do_scrolling = false;
  var scrollable_element = jQuery('body.fixed-width #shopp .category .products .row ul');
  
  if(scrollable_element.length > 0){
    do_scrolling = true;
    scrollable_element.css('position', 'relative');
    var fixed_total_width = scrollable_element.outerWidth(true);
  }
  
  if(!do_scrolling){
    var scrollable_element = jQuery('body.fixed-width #checkout fieldset');
    scrollable_element.css('position', 'relative');
    var fixed_total_width = 0;
    scrollable_element.find('.cocontainer').each(function(i, el){
      fixed_total_width = fixed_total_width + jQuery(el).outerWidth(true);
    });
    do_scrolling = true;
    //we cannot use the normal method of using # because we are scrolling internal content internally (via positioning right)
    //We must determine the right offset of each # linked element and scroll to it via positioning.
    jQuery(scrollable_element).find('a[href^=#]').each(function(i, el){
      var to_element = jQuery(jQuery(el).attr('href'));
      var position = to_element.offset();
      jQuery(el).click(function(){
        scrollable_element.stop().animate({'right': position.left}, 450, 'linear');
        return false;
      })
    });
  }
  
  if(do_scrolling === true){
    var window_width = jQuery(window).width();
    jQuery(window).bind('resize', function(){
      window_width = jQuery(window).width();
    });
    
    var position = 0;
    jQuery('html').mousewheel(function(e, d){
      if(d > 0){
        //move right
        move_left();
      } else {
        //move left
        move_right();
      }
    });
  
    jQuery('#scroll-r').hover(
      function(){
        var max_pos = fixed_total_width - window_width;
        move_products_pos('right', max_pos + 1, 1200);
      },
      function(){
        scrollable_element.stop();
      }
    );
  
    jQuery('#scroll-l').hover(function(){
        move_products_pos('left', 0, 1200);
      },
      function(){
        scrollable_element.stop();
      }
    );
  }
}

var move_products_pos = function(dir, move_in_increments, delay){
  //get direction value

  if(typeof(delay) == 'undefined'){
    delay = 500;
  }

  var cur_pos = parseInt(scrollable_element.css('right').replace('px', '')); //this is set to right for a reason...
  if(!cur_pos){
    cur_pos = 0;
  }
  var max_pos = fixed_total_width - window_width;      
  move_to = false;
    
  if(dir == 'left'){  
    if(move_in_increments === 0){
      move_to = 0;
    } else {
      if(cur_pos > 0){
        move_to = cur_pos - move_in_increments;
        if(move_to < 0){
          move_to = 0;
        }
      }
    }

  } else {
    if(cur_pos < max_pos){
      move_to = cur_pos + move_in_increments;
    }
  }
  if(move_to !== false){
    scrollable_element.stop().animate({'right': move_to}, delay);
  }
};

var move_right = function(){
  move_products_pos('right', 420);
};

var move_left = function(){
  move_products_pos('left', 420);
};


/*** About Page Custom Post Form ***/
$('textarea#comment').css({
	'height':'16px',
	'color':'#757575'
});

$('.magicfields').css('display','none');

$('textarea#comment').focus(function(){
	$(this).css({
		'height':'40px',
		'color':'#FFFFFF'
	});
	$('.magicfields').css({
		'display':'block',
		'color':'#FFFFFF'
	});
});

$('textarea#comment').blur(function(){
	if($(this).val() == ''){
		$(this).css({
			'height':'16px',
			'color':'#757575'
		}).val("What's on your mind?");
		$('.magicfields').css('display','none');
	} else {
		$(this).css({
			'height':'40px',
			'color':'#FFFFFF'
		});
		$('.magicfields').css({
			'display':'block',
			'color':'#FFFFFF'
		});
	}
});

/*** Misc Styling Fixes ***/
$('#participateemail').focus(function(){
	$(this).css('color','#FFFFFF');
});
$('#participateemail').blur(function(){
	$(this).css('color','#AAAAAA');
});

if($('#content').hasClass('oops404')){
	setTimeout(function(){		
		var url = "http://localhost/ecomtest/";    
		$(location).attr('href',url);
	}, 5000);
};

/*** Shopping Cart Page onChange ***/
$('#shipping-country').change(function(){
	$('.quantityc').find('.update-button').eq(0).click();
});

/*** Billing/Shipping Address ***/

// Disable Checkbox first
$('#same-shipping').click();

function copyInput(){
	$('#shipping-address').val( $('#billing-address').val());
	$('#shipping-city').val( $('#billing-city').val());
	var bstate = $('#billing-state').val();
	$('#shipping-state').selectOptions(bstate);
	$('#shipping-state').val( $('#billing-state').val());
	$('#shipping-postcode').val( $('#billing-postcode').val());
	var bcountry = $('#billing-country').val();
	$('#shipping-country').selectOptions(bcountry); 
};

function clearInput(){
	$('#shipping-address').val('');
	$('#shipping-city').val('');
	var bstate = $('#shipping-state').val('');
	$('#shipping-state').selectOptions(bstate);
	$('#shipping-state').val('');
	$('#shipping-postcode').val('');
	var bcountry = $('#shipping-country').val('');
	$('#shipping-country').selectOptions(bcountry); 
};

$('#same-shipping').click(function(){
	if ($(this).hasClass('activated')){
		clearInput();
		$('#same-shipping').attr('checked','');
		$(this).removeClass('activated');
	} else {
		$(this).addClass('activated');
		copyInput();
		$('#same-shipping').attr('checked', true);
	};
});

if ($('#same-shipping').is(':checked')) {$('#billingdets').find('input[type!=checkbox],select').change(function(){copyInput();});};
	
// Product Page Lightbox	
	$('a.shopp-thickbox').click(function(){
		var imgurl = $('a.shopp-thickbox').attr('href');
		var imgname = $('#proddetails').children('h2').text();
		
		$('#largeimg').attr('src',imgurl).attr('alt',imgname);
		
		$('a.shopp-thickbox').removeAttr('href');
		$('a.shopp-thickbox').attr('title','Clicking to view larger image');
		var h = $(window).height();
		var w = $(window).width();
    	$('#facebox-dim')
			.height(h)
			.width(w)
			.css({
				display:'block'
				})
			.fadeIn();
		$('#largeimg')
			.fadeIn()
			.css({
				display:'block'
				});
			
		$(window).resize(function(){
	    $('#facebox-dim').height($(window).height());
	    $('#facebox-dim').width($(window).width());
		});	
			
	});
	$('#facebox-dim').click(function(){		
		var retimg = $('#largeimg').attr('src');
		$('a.shopp-thickbox').attr('href',retimg);
		$('#largeimg').attr('src','');
		$('#largeimg').fadeOut();
		$('#facebox-dim').fadeOut();
	});


// end jquery
});