/**

 * Retrieves background image URL from the CSS <body> 'background-image' and

 * appends an <img> element for the stretchable background image.

 */

function resetBg() {

	if ($('#bg').length == 0) {

		var bgUrl = $('body').css('background-image').replace(/^url|[\(\)"]/g, '');

		$('body').css('background-image', 'none')

             .prepend('<div id="bg"><img src="' + bgUrl + '" width="1600" height="1100" alt="" /></div>');

	}

	

	var bg    = $('#bg');

	var bgImg = $('img', bg);

	var winW  = $(window).width();

	var winH  = $(window).height();

	var initW = bgImg.width();

	var initH = bgImg.height();

	var ratio = initH / initW;

	

	if (winW < 1000) {

		winW = 1000;

	}



	bgImg.width(winW);

	bgImg.height(winW * ratio);

	

	if(bgImg.height() < winH){

		bgImg.height(winH);

		bgImg.width(bgImg.height() / ratio);

	}	

} // resetBg()



/**

 * Resizes the width of the #menu container to expose the #wrapper's scroll bar.

 */

function resetMenu() {

	$('#menu').width($('#container').width());

} // resetMenu()



function carousel1_initCallback(carousel, state) {

}



/**

 * Gets called on carousel1 load.

 */

function carousel1_itemLoadCallback(carousel, state) {

  if (carousel.has(carousel.first, carousel.last)) {

    return;

  }



  $.get(

    carousel_datasource + carousel.first + '/' + carousel.last,

    function(data) {

      $('.tooltip').remove();

      carousel1_itemAddCallback(carousel, carousel.first, carousel.last, data);

      // add tooltip

      $('.carousel img[title]').tooltip({

        effect: 'slide'

      });

    },

    'json'

  );

} // carousel1_itemLoadCallback()



/**

 * Gets called on when adding item to the carousel1.

 */

function carousel1_itemAddCallback(carousel, first, last, data) {

  carousel.size(data.total);

  resizeCarousel1(carousel);



  var i = 0;

  $.each(data.items, function(index, value) {

    item_html  = '';

    item_html += '<a href="' + value['url'] + '">';

    item_html += '<img src="' + value['image'] + '" width="135" height="135" alt="" title="' + value['title'] + '" />';

    item_html += '</a>';

    carousel.add(first + i++, item_html);

  });



  carousel.reload();

} // carousel1_itemAddCallback()



/**

 * Resizes horizontal carousel at the bottom of the page.

 *

 * requires js/jcarousel-0.2.4.min.js

 * requires js/tools-1.1.2.min.js

 */

function resetCarousel1() {

	if ($('.jcarousel-skin-penny1').length > 0) {

		

		var carousel = $('.carousel').data('jcarousel');

		

		if (carousel == null) {

			$('.carousel').jcarousel({

        initCallback    : carousel1_initCallback,

        itemLoadCallback: carousel1_itemLoadCallback

      });

			carousel = $('.carousel').data('jcarousel');

		}



    resizeCarousel1(carousel);

    carousel.reload();

	}

} // resetCarousel1()



function resizeCarousel1(carousel) {

  var space = $('#container').width() - 100;

  var count = Math.floor(space / 140); // visible slots



  if (count > carousel.size()) {

    count = carousel.size();

  }



  var wrapW = 137 * count;

  var clipW = wrapW + 30;



  $('.jcarousel-skin-penny1 .jcarousel-clip-horizontal').width(wrapW);

  $('.jcarousel-skin-penny1 .jcarousel-container-horizontal').width(clipW);



  carousel.options['scroll']  = count;

  carousel.options['visible'] = count;

}



/**

 * Gets called on carousel2 load.

 */

function carousel2_itemLoadCallback(carousel, state) {

  if (carousel.has(carousel.first, carousel.last)) {

    return;

  }



  $.get(

    carousel_datasource + carousel.first,

    function(data) {

      carousel2_itemAddCallback(carousel, carousel.first, carousel.last, data);

    },

    'json'

  );

} // carousel2_itemLoadCallback()



/**

 * Gets called on when adding item to the carousel2.

 */

function carousel2_itemAddCallback(carousel, first, last, data) {

  carousel.size(data.total);



  item_html = '<ul id="set'+first+'">\n';



  $.each(data.items, function(index, value) {

    item_html += '<li>\n';

    item_html += '  <a href="' + value['image2'] + '" rel="g' + first + '">\n';

    item_html += '    <img src="' + value['image_tn'] + '" width="190" height="238" alt="" />\n';

    item_html += '  </a>\n';

    item_html += '  <h2>' + value['caption'] + '</h2>\n';

    item_html += '  <p>' + value['subcaption'] + '</p>\n';

    item_html += '  <div style="display: none;">\n';



    if (value['image3'].length > 0) {

      item_html += '<a href="' + value['image3'] + '" rel="g' + first + '">\n';

      item_html += '  <img src="' + value['image3'] + '" alt="" />\n';

      item_html += '</a>\n';

    }



    if (value['image4'].length > 0) {

      item_html += '<a href="' + value['image4'] + '" rel="g' + first + '">\n';

      item_html += '  <img src="' + value['image4'] + '" alt="" />\n';

      item_html += '</a>\n';

    }



    if (value['image'].length > 0) {

      item_html += '<a href="' + value['image'] + '" rel="g' + first + '">\n';

      item_html += '  <img src="' + value['image'] + '" alt="" />\n';

      item_html += '</a>\n';

    }



    item_html += '  </div>\n';

    item_html += '</li>\n';

  });



  item_html += '</ul>\n';



  carousel.add(first, item_html);



  // add lightbox

  $('#set'+first+' li').each(function(i){

    $('a', this).fancybox({

      'showCloseButton' : false,

      'titlePosition'   : 'inside',

      'titleFormat'     : formatCarousel3Title,

      'overlayColor'    : '#000',

      'overlayOpacity'  : 0.75,

      'currentItem'     : $(this)

    });

  });



} // carousel2_itemAddCallback()



/**

 * Renders carousel style2 when present.

 *

 * requires js/jcarousel-0.2.4.min.js

 */

function resetCarousel2() {

	var c2 = $('.carousel2');

	var bg = $('.jcarousel-bg', carousel);



	if ($('.carousel2').length > 0) {

		var carousel = $('.carousel2').data('jcarousel');

		if (carousel == null) {

			$('.carousel2').jcarousel({

        scroll: 1,

        itemLoadCallback: carousel2_itemLoadCallback

      });

			carousel = $('.carousel2').data('jcarousel');

		}



		if (bg.length == 0) {

			//carousel.prepend('<img src="images/carousel2_bg.png" width="100%" height="100%" class="jcarousel-bg" />');

		}



		// fit carousel in the available area

		var areaH = $(window).height() - 125; // #logo + 17

		if (areaH < 684) {

			c2.addClass('for1024x768');

		} else {

			c2.removeClass('for1024x768');

		}



    carousel.reset();



		$('.jcarousel-item li', carousel).each(function(i){



			// add fancybox

			$('a', this).fancybox({

				'showCloseButton' : false,

				'titlePosition'   : 'inside',

				'titleFormat'     : formatCarousel3Title,

				'overlayColor'    : '#000',

				'overlayOpacity'  : 0.75,

				'currentItem'     : $(this)

			});

			

		});

	}

} // resetCarousel2()



/**

 * Customizes fancybox layout.

 *

 * requires js/fancybox/jquery.fancybox-1.3.1.pack.js

 */

function formatCarousel3Title(title, currentArray, currentIndex, currentOpts) {

	var paragraphs = '';

	$('p', currentOpts.currentItem).each(function(index){

	    paragraphs += '<p>' + $(this).html() + '</p>';

	});

	

	var returnHtml = '<div id="fancybox-info">'

		+ '<h2>' + $('h2', currentOpts.currentItem).text() + '</h2>'

		+ paragraphs

		+ '<a href="javascript:;" onclick="$.fancybox.close();" class="close">Close</a>';

	

	if (undefined == window.showImageCount)

	{

		returnHtml += '</div>';

	} else {

		returnHtml += 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';

	}

	

	return returnHtml;

} // formatCarousel3Title()



/**

 * Gets called on carousel3 load.

 */

function carousel3_itemLoadCallback(carousel, state) {

  if (carousel.has(carousel.first, carousel.last)) {

    return;

  }



  $.get(

    carousel_datasource + carousel.first,

    function(data) {

      carousel3_itemAddCallback(carousel, carousel.first, carousel.last, data);

    },

    'json'

  );

} // carousel3_itemLoadCallback()



/**

 * Gets called on when adding item to the carousel3.

 */

function carousel3_itemAddCallback(carousel, first, last, data) {

  carousel.size(data.total);



  item_html = '<ul id="set'+first+'">\n';



  $.each(data.items, function(index, value) {

    item_html += '<li>\n';

    item_html += '<a href="' + value['image'] + '" rel="g1">';

    item_html += '<img src="' + value['image_tn'] + '" width="240" height="240" alt="" title="' + value['name'] + '" />';

    item_html += '</a>';

    if (value['name'].length > 0) item_html += '<h2 class="caption">' + value['name'] + '</h2>';

    item_html += '<p>' + value['caption'] + '</p>';

    item_html += '</li>\n';

  });



  item_html += '</ul>\n';



  carousel.add(first, item_html);



  // add lightbox

  $('#set'+first+' li').each(function(i){

    $('a', this).fancybox({

      'showCloseButton' : false,

      'titlePosition'   : 'inside',

      'titleFormat'     : formatCarousel3Title,

      'overlayColor'    : '#000',

      'overlayOpacity'  : 0.75,

      'currentItem'     : $(this)

    });

  });



  // do we have less 6 items?

  if ($('.carousel3 img').length <= 6) {

    $('.carousel3').addClass('for6x2');

  }

} // carousel3_itemAddCallback()



/**

 * Renders carousel style3 when present.

 *

 * requires js/jcarousel-0.2.4.min.js

 */

function resetCarousel3() {

	if ($('.carousel3').length > 0) {

		var carousel = $('.carousel3').data('jcarousel');

		if (carousel == null) {

			$('.carousel3').jcarousel({

        scroll: 1,

        itemLoadCallback: carousel3_itemLoadCallback

      });



			carousel = $('.carousel3').data('jcarousel');

		}



		// fit carousel in the available area

		var areaH = $(window).height() - 125; // #logo + 17

		if (areaH < 684) {

			$('.carousel3').addClass('for1024x768');

      $('.jcarousel-skin-penny3').css('padding-top', '0px');

		} else {

			$('.carousel3').removeClass('for1024x768');

      $('.jcarousel-skin-penny3').css('padding-top', '100px');

		}



    carousel.reset();

	}

} // resetCarousel3()



/**

 * Resizes the #content width.

 */

function resetContent() {

	if ($('#content').length > 0) {

		var containerW = $('#container').width();

		var content    = $('#content');

		var contentP   = parseInt(content.css('padding-left')) + parseInt(content.css('padding-right'));

		var contentW   = content.width() + contentP;

		var pagetitle  = $('#pagetitle');

		var pagetitleP = parseInt(pagetitle.css('padding-left')) + parseInt(pagetitle.css('padding-right'));

		var pagetitleW = pagetitle.width() + pagetitleP;

		var W          = containerW - pagetitleW - pagetitleP - 30;

		

		// #content.wide

		if (content.hasClass('wide')) {

			$('#content').width(W);

			return 0;

		}

		

		// default width

		if (W > 980) {

			W = 980;

		}		

	}

} // resetContent()



/**

 * Resizes the width of the Google Map iFrame.

 */

function resetGoogleMap() {

	if ($('#map').length > 0) {

		$('#map').width($('#content').width() - $('#store-search-results').width() - 20);

	}

} // resetGoogleMap()



/**

 * Resizes #product-image and #product-info.

 */

var resetProductPageExecuted = false;

function resetProductPage() {

	if ($('body.product-page').length > 0) {

		var container  = $('#container');

		var submenu    = $('#submenu');

		var image      = $('#product-image');

		var info       = $('#product-info');

		var carousel   = $('.jcarousel-skin-penny1');

		var areaW      = container.width() - image.offset().left - 60;

		var areaH      = carousel.offset().top - submenu.offset().top - 20;

		

		$('img', image).removeAttr('style');

		if ((($('img', image).height() > areaH)) || ($('img', image).width() > 350)) {

			if (areaH < 250) {

				areaH = 250;

			}

			$('img', image).height(areaH);

			$('img', image).width(image.width() * (areaH / image.width()));



      if ($('img', image).width() > 350) {

        var imageRatio = $('img', image).height() / $('img', image).width();

        $('img', image).width(350);

        $('img', image).height(350 / imageRatio);

      }

		}

		

		info.width(940 - image.offset().left - image.width());

		

		if (!resetProductPageExecuted) {

      resetProductPageExecuted = true;

			image.hide();

			info.hide();

			image.show('slide', {easing: 'swing'}, 1000, function(){

				info.show('slide', {easing: 'swing'}, 500);

			});

		}

	}

} // resetProductPage()



/**

 * Executes all layout functions and binds the function to the 'window.resize' event.

 */

function resetLayout() {

		resetBg();

		resetContent();

		resetGoogleMap();

		resetCarousel1();

		resetCarousel2();

		resetCarousel3();

		resetProductPage();

		resetMenu();

} // resetLayout()



$(document).ready(function(){

	$(window).resize(function(){

    resetLayout();

  });

  $(window).resize();



	// requires 'js/superfish-1.4.8.js'

	$('#menu .main').superfish({

		autoArrows: false

		//speed:      0,

	});

	

	// lightbox login

	

	$('.login-lightbox').fancybox({

		'type'            : 'iframe',

		'width'           : 300,

		'height'          : 170,

		'overlayColor'    : '#000',

		'overlayOpacity'  : 0.75

	});



		

	// email this product

	$('#emailPage').fancybox({

		'type'            : 'iframe',

		'width'           : 320,

		'height'          : 337,

		'overlayColor'    : '#000',

		'overlayOpacity'  : 0.75

	});

	

	// product zoom

	$('#product-image a').fancybox({

		'showCloseButton' : false,

		'titlePosition'   : 'inside',

		'titleFormat'     : formatCarousel3Title,

		'overlayColor'    : '#000',

		'overlayOpacity'  : 0.75,

		'currentItem'     : $('#product-image'),

    'margin'          : 50

	});

	

	// print product page

	$("#printPage").click(function(){

		window.print();

		return false;

	});



	// font styling

	//Cufon.replace('#logo', {fontFamily: 'Adobe Garamond Pro'});

	Cufon.replace('.product-page #product-info h2', {fontFamily: 'Adobe Garamond Pro'});

	Cufon.replace('#menu ul.main>li>a', {fontFamily: 'Adobe Caslon Pro', hover: true, textShadow: '#000 -1px -1px'});

	Cufon.replace('#submenu', {fontFamily: 'Adobe Caslon Pro', hover: true});

	Cufon.replace('#pagetitle', {fontFamily: 'Adobe Caslon Pro'});

});



$(window).load(function(){

//  alert('1');

});



function validateContactUs()

{

	fields  = [['name', '-Please enter your name']];

	customs = [['email', 'email']];

	

	return validateForm(fields, customs);

}



function validateRegister()

{

	fields  = [

				['name', '-Please enter your name'],

				['password', '-Please enter a desired password'],

				['phone', '-Please enter your phone number'],

				['store', '-Please enter your store name'],

				['position', '-Please enter your position']

			  ];

	customs = [['email', 'email']];

	

	return validateForm(fields, customs);

}



function validateMyAccount()

{

	fields  = [

				['name', '-Please enter your name'],

				['phone', '-Please enter your phone number'],

				['store', '-Please enter your store name'],

				['position', '-Please enter your position']

			  ];

	customs = [['email', 'email']];

	

	return validateForm(fields, customs);

}



function validateEmailFriend()

{

	fields  = [

				['your_name', '-Please enter your name'],

				['friends_name', '-Please enter your friend\'s name'],

			  ];

	customs = [

				['email', 'your_email'],

				['email', 'friends_email']

			  ];

	

	return validateForm(fields, customs);



}



function validateResetPassword()

{

	fields  = [

				['password', '-Please enter a new password'],

			  ];

	customs = [['confirm', 'password', 'password2', '-Your passwords do not match']];

	

	return validateForm(fields, customs);

}



/* gMaps */

var map;

var geocoder;



function load() {

  if (GBrowserIsCompatible()) {

    geocoder = new GClientGeocoder();

    map = new GMap2(document.getElementById('map'));

    map.addControl(new GSmallMapControl());

    map.addControl(new GMapTypeControl());

    map.setCenter(new GLatLng(40, -100), 4);

  }

  

  $("#loc-us").click(function(){

  	$("#zipcode_form").css('display', '');

  });

  

  $("#loc-international").click(function(){

  	$("#zipcode_form").css('display', 'none');

  	$("#results_txt").html('');

  	searchLocationsNear('international', '');

  });

  

  $("#loc-islands").click(function(){

  	$("#zipcode_form").css('display', 'none');

  	$("#results_txt").html('');

  	searchLocationsNear('island', '');

  });

  

  resetLayout();

}



function searchLocations() {

  var address = document.getElementById('addressInput').value;

  geocoder.getLatLng(address, function(latlng) {

    if (!latlng) {

      alert(address + ' not found');

    } else {

      $("#store-search-results").css('overflow-y', 'scroll');

      

      var resultsTxt = 'These U.S. locations are within <strong>';

      resultsTxt += $("#radiusSelect").val() + ' miles</strong> of ';

      resultsTxt += 'your zip code: <strong>' + $("#addressInput").val() + '</strong>';

      $("#results_txt").html(resultsTxt);

      

      searchLocationsNear('us', latlng);

    }

    

    resetLayout();

  });

}



function searchLocationsNear(searchType, center) {

  switch (searchType)

  {

  	case 'us':

  		var radius = document.getElementById('radiusSelect').value;

  		var searchUrl = 'location_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&type=us';

  		break;

  		

  	case 'international':

  	case 'island':

  		var searchUrl = 'location_search.php?&type=' + searchType;

  		break;

  }

  

  

  GDownloadUrl(searchUrl, function(data) {

    var xml = GXml.parse(data);

    var markers = xml.documentElement.getElementsByTagName('marker');

    map.clearOverlays();



    var sidebar = document.getElementById('show_results');

    sidebar.innerHTML = '';

    

    if (markers.length == 0) {

      sidebar.innerHTML = 'No results found.';

      map.setCenter(new GLatLng(40, -100), 4);

      return;

    }



    var bounds = new GLatLngBounds();

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

      var name      = markers[i].getAttribute('name');

      var address   = markers[i].getAttribute('address');

      var address2  = markers[i].getAttribute('address2');

      var address3  = markers[i].getAttribute('address3');

      var city      = markers[i].getAttribute('city');

      var state     = markers[i].getAttribute('state');

      var zip       = markers[i].getAttribute('zip');

      var phone     = markers[i].getAttribute('phone');

      var email     = markers[i].getAttribute('email');

      var distance  = parseFloat(markers[i].getAttribute('distance'));

      var point     = new GLatLng(parseFloat(markers[i].getAttribute('lat')),

                              parseFloat(markers[i].getAttribute('lng')));

      

      var marker = createMarker(point, name, address, address2, address3, city, state, zip, phone, email);

      map.addOverlay(marker);

      var sidebarEntry = createSidebarEntry(marker, name, address, address2, address3, city, state, zip, phone, email, distance, searchType);

      sidebar.appendChild(sidebarEntry);

      bounds.extend(point);

    }

    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

  });

}



 function createMarker(point, name, address, address2, address3, city, state, zip, phone, email) {

   var marker = new GMarker(point);

   var html = '<div style="color: #000;"><b>' + name + '</b> <br/>' + address;

   if (address2.length > 0) {html += '<br />' + address2;}

   if (address3.length > 0) {html += '<br />' + address3;}

   html += '<br />' + city + ', ' + state + ' ' + zip + '<br />';

   html += phone + '<br />' + email + '<br />';

   

   var gAddress = address;

   if (address2.length > 0) { gAddress = address2; }

   gAddress += ' ' + city + ' ' + state + ' ' + zip;

   html += '<a href="http://maps.google.com/maps?f=d&hl=en&geocode=&daddr=' + encodeURI(gAddress) + '" style="color: #000;" target="_newwin">Get Directions</a>';

   

   html += '</div>';

   

   GEvent.addListener(marker, 'click', function() {

     marker.openInfoWindowHtml(html);

   });

   return marker;

 }



 function createSidebarEntry(marker, name, address, address2, address3, city, state, zip, phone, email, distance, searchType) {

   var li = document.createElement('li');

   

   var html = '<h2 style="margin: 0;">' + name + '</h2><p>' + address;

   if (address2.length > 0) {html += '<br />' + address2;}

   if (address3.length > 0) {html += '<br />' + address3;}

   html += '<br />' + city + ', ' + state + ' ' + zip + '<br />';

   html += phone + '<br />' + email;

   

   if (searchType == 'us') {html += '<br />Approximate Distance: ' + distance.toFixed(1);} 

   

   var gAddress = address;

   if (address2.length > 0) { gAddress = address2; }

   gAddress += ' ' + city + ' ' + state + ' ' + zip;

   html += '<br/><a href="http://maps.google.com/maps?f=d&hl=en&geocode=&daddr=' + encodeURI(gAddress) + '" target="_newwin">Get Directions</a>';

    

   html += '</p>';

    

   li.innerHTML = html;

   li.style.cursor = 'pointer';

    

   GEvent.addDomListener(li, 'click', function() {

     GEvent.trigger(marker, 'click');

   });

   GEvent.addDomListener(li, 'mouseover', function() {

     li.style.backgroundColor = '#262626';

   });

   GEvent.addDomListener(li, 'mouseout', function() {

     li.style.background = 'none';

   });

   return li;

 }
