var debug = false;

$(document).ready(function(){


	/* PRODUCTS CAROUSEL
	   uses jquery.carousel.js
	*/
	$("#content-alpha div.products-carousel").carousel({
		dispItems: 4,
		slideEasing: "easeInOutCubic"
	});

	$("#content-beta div.products-carousel").carousel({
		dispItems: 2,
		slideEasing: "easeInOutCubic"
	});

	// Tooltips for Carousel
	$(".products-carousel ul li a").tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		showBody: " - ",
		opacity: 1,
		top: 1,
		left: -10
	});


	/* EXPAND/COLLAPSE TEXT
	   added 'read more' text using jquery.expander.js
	*/

	// add to store homepage 'message from shadow' area using defaults
	$("div#message-from-shadow p").expander();
	// add to downloads description text
	$('div.digital div#product-description p').expander({
		slicePoint: 600
	});

	// add to homepage coming soon
	$('div#coming-soon dd.description').expander({
		slicePoint: 100
	});
	$(".list-shows p").expander({
		slicePoint: 150
	});



	function createCookie(name,value) {
		var date = new Date();
		date.setTime(date.getTime()+(1*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
		if(debug)alert('cookie set '+name+' to '+value);
     }


	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
	}

	/* Retrieve or set Cookie for Discography checkbox */

	function checkboxCookie(chkbox,useCheckboxFormVal,defaultValue) {

		var chkboxVal = 'no';
		if (!defaultValue) defaultValue = 'yes';
		if (!useCheckboxFormVal) {

			//read checkbox from cookie
			var chkboxVal = readCookie(chkbox);
			if (!chkboxVal) {
				chkboxVal = defaultValue;
				createCookie(chkbox,chkboxVal);
			}
			if(debug)alert('checkbox '+chkbox+' is '+chkboxVal);
		}
		else {
			if ($('#'+chkbox).is(':checked')) chkboxVal = 'yes';
			createCookie(chkbox,chkboxVal);
		}

		if (chkboxVal == 'yes') $("#"+chkbox).attr("checked", "checked");
		else $("#"+chkbox).attr("checked", "");

		return chkboxVal;

	}




	/* DISCOGRAPHY UI AND SCRIPTS
	   attaches jquery ui for the slider and adds ajax requests for the list of releases
	   checks cookie values to build form
	*/

	function getDiscogs(gotoPage,useRangeFormVal,useSearchFormVal,useCheckboxFormVal) {

		var ft_album = checkboxCookie('ft_album',useCheckboxFormVal);
		var ft_single = checkboxCookie('ft_single',useCheckboxFormVal);
		var ft_compilation = checkboxCookie('ft_compilation',useCheckboxFormVal);
		var ft_production = checkboxCookie('ft_production',useCheckboxFormVal);
		var ft_mix = checkboxCookie('ft_mix',useCheckboxFormVal);
		var ft_dvd = checkboxCookie('ft_dvd',useCheckboxFormVal);
		var ft_calitex = checkboxCookie('ft_calitex',useCheckboxFormVal);
		var ft_other = checkboxCookie('ft_other',useCheckboxFormVal,'no');
		var ft_bootlegs = checkboxCookie('ft_bootlegs',useCheckboxFormVal,'no');

		// if the var is set to false, then read from cookie
		// if true or value the use the value

		if (useRangeFormVal) {
			if (useRangeFormVal != 'true' && useRangeFormVal != true) {
				if(debug)alert('going to '+useRangeFormVal);
				range = useRangeFormVal;
			}
			else {
				if(debug)alert('writing range');
				range = $("#amount").val();
				// if doing a search, dont cookie the range (which search is always searching full range)
				if (!useSearchFormVal) createCookie('range',range);
				createCookie('page',0);
			}
		}
		else {

			if(debug)alert('reading range');
			var range = readCookie('range');
			if (!range || range == '') {
				if(debug)alert('WARNING SETTING DEFAULT RANGE');
				if(debug)alert('which is '+range);
				range = defaultMinDiscogYear+' - '+defaultMaxDiscogYear;
			}
			if(debug)alert('range is '+range);

		}


		page = gotoPage;
		if (!page) page = 0;
		if (debug) alert('writing page cookie : '+page);
		createCookie('page',page);


		if(debug)alert('page is '+page);


		if (useSearchFormVal) {
			if(debug)alert('writing search');
			search = $("#searchTxt").val();
			createCookie('search',search);
			createCookie('page',0);
		}
		else {
			var search = readCookie('search');
			if (!search || search == 'undefined') search = '';
			if(debug)alert('reading search is '+search);
		}


		var view_checked = 'yes';
		if (ft_album == 'no' && ft_single == 'no' && ft_production == 'no' && ft_compilation == 'no' && ft_mix == 'no' && ft_dvd == 'no' && ft_calitex == 'no' && ft_other == 'no' && ft_bootlegs == 'no') view_checked = 'no';

		$.get("/discography/ajax", { view_checked: view_checked, page: page, search: search, range: range, ft_album: ft_album, ft_single: ft_single,ft_compilation: ft_compilation, ft_production: ft_production, ft_mix: ft_mix, ft_dvd: ft_dvd, ft_calitex: ft_calitex, ft_other: ft_other, ft_bootlegs: ft_bootlegs }, function(data){
			$('#discogs').html(data); //+' on page '+page

			// change the pagnation state/color
			$('#Pagination > a:contains('+ page +')').filter(function() {
				if( $(this).text() == page )
					$(this).css('color','#666666');
			})
		});
	}


	var storedFilters = new Array();

	function getRangeVar(which) {
		// get the min and max from cookie
		range = readCookie('range');
		if (range) {
			var rangeSplit = range.split(" - ");
			var rangeMin = rangeSplit[0];
			var rangeMax = rangeSplit[1];

		}
		else {
			if(debug)alert('No range set !!!!!!');
			var range = defaultMinDiscogYear+' - '+defaultMaxDiscogYear;
			var rangeMin = defaultMinDiscogYear;
			var rangeMax = defaultMaxDiscogYear;
		}
		if (which == 'min') return rangeMin;
		else return rangeMax;

	}


	function clearFilters() {
		storedSliderMin = $('#slider-range').slider('values', 0);
		storedSliderMax = $('#slider-range').slider('values', 1);

		$('input[type="checkbox"]').each(function(i){
			//storedFilters[i] = this.checked;
			this.disabled = true;
			//alert('got value of checkbox i = ' + i + ' value = ' + this.checked)
		});

		$('input[type="checkbox"]').attr('checked','true');
		$('#slider-range').slider('values', 0, [defaultMinDiscogYear]);
		$('#slider-range').slider('values', 1, [defaultMaxDiscogYear]);

		$('#slider-range').slider('disable');
	}

	function resetFilters() {
		$('input[type="checkbox"]').each(function(i){
			this.disabled = false;
		});

		$('#slider-range').slider('enable');

		var rangeMin = getRangeVar('min');
		var rangeMax = getRangeVar('max');

		//alert('storedSliderMin: ' + storedSliderMin + ' storedSliderMax: ' + storedSliderMax)
		$('#slider-range').slider('values', 0, [rangeMin]);
		$('#slider-range').slider('values', 1, [rangeMax]);
	}

	// the discography functions are only initalized on pages that have the #discog-get form
	if( $("#discog-get").length ) {

		var rangeMin = getRangeVar('min');
		var rangeMax = getRangeVar('max');

		range = readCookie('range');
		if(debug)alert('should be '+range);
		if(debug)alert('But is '+rangeMin+' '+rangeMax);
		$("#slider-range").slider({
			range: true,
			min: defaultMinDiscogYear,
			max: defaultMaxDiscogYear,
			values: [rangeMin, rangeMax],
			slide: function(event, ui) {
				$("#amount").val(ui.values[0] + ' - ' + ui.values[1]);
			},
			stop: function(event, ui) {
				//alert($("#amount").val());
				getDiscogs(0,true,false);
				$("#amount").val(ui.values[0] + ' - ' + ui.values[1]);
			}
		});

		$("#amount").val($("#slider-range").slider("values", 0) + ' - ' + $("#slider-range").slider("values", 1));

		// on Page Load

		$("input#searchTxt").val(readCookie('search'));
		//getDiscogs(readCookie('page'),readCookie('range'),readCookie('search'));
		getDiscogs(readCookie('page'),false,false);


		// if session search text is set
		if ($("#searchTxt").val() != '') clearFilters();


		$("input#searchTxt").keypress(function (e) {
			// removed while testing
			if (e.which == 13) { getDiscogs(0,true,true); }
		});

		$('input:checkbox').click(function() {
				getDiscogs(0,false,false,true);
		});

		$('#searchBtn').click(function() {
				getDiscogs(0,false,true);
		});

		$('ul.pagnation a').live("click",function() {
			//var pageHash = this.href.substring(1);
			var pageHash = this.hash.substr(1);
			if(!pageHash || pageHash == '') pageHash = 0;
			getDiscogs(pageHash,false,false);
		});

		var firstChar = true;

		$('input#searchTxt').keyup(function() {
			if($('input#searchTxt').val().length > 0) {
				if(firstChar) {
					clearFilters();
				}
				firstChar = false;
			} else {
				resetFilters();
				firstChar = true;
				getDiscogs(0,false,true);
				//alert('done');
			}
			//update timeline display
			$("#amount").val($('#slider-range').slider('values', 0) + ' - ' + $('#slider-range').slider('values', 1));
		});
	}


	/* DISCOGRAPHY IMAGE SWAPPER
	   swaps the images on the discography item pages from the thumbnails to the main image
	*/
	$('img.release_thumbs:first').addClass("active");

	$('img.release_thumbs').click(function() {
		var largePath = $(this).attr("src");
		var largeHeight = 300;
		var largeWidth = 300;

		// Image preload process
		var imagePreloader = new Image();
		imagePreloader.src = largePath;

		imagePreloader.onload = function() {
			// get dimensions from preloader
			largeHeight = imagePreloader.height;
			largeWidth = imagePreloader.width;

			// set src and dimensions on the release image in the page
			$("img#release_init").attr('src', largePath );
			$("img#release_init").attr('height', largeHeight );
			$("img#release_init").attr('width', largeWidth );
		};

		$('img.release_thumbs').removeClass('active');
		$(this).addClass("active");
	});



	/* SHOPPING CART COOKIE TEXT WRITER -- this is now being handled by the TOPSPIN object
		Looks for a cookie set by the store to figure out if the visitor has items in his or her cart

	var numCartItems = readCookie('mivacart');

	if (numCartItems == null) {
		$('span#shopping-cart-itemsCount').text('(0)');
	} else if (numCartItems == '1') {
		$('span#shopping-cart-itemsCount').text('(1)');
	}	else {
		$('span#shopping-cart-itemsCount').text('('+ numCartItems +')');
	}
*/

	/* FORM INPUT PLACEHOLDER TEXT
	   adds 'placeholder' text in text input fields based on the element's title
	   that disappears once the element gets focus
	*/
	$('input[type=text]').each(function(i) {
		if($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});

	$('input[type=text]').focus(function(){
		if($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	});

	$('input[type=text]').blur(function(){
		if($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});


	/* CSS TWEAKS
	   these tweaks take advantage of jquery's more advanced selectors to allow for better cross-browser support
	   or simply fill in functionality that isn't available in miva
	*/

	// add 'last' class to appropriate elements in the store
	$('body#body-store div#content-beta div#featured-products dl:last').addClass('last');
	$('body#body-store div#content-alpha table#products-listing tr:last').addClass('last');

	$("#subcategory-filter-select").change(function() {
		 cat_code = $('select#subcategory-filter-select').val();
		  window.location.href = "/Merchant2/merchant.mvc?Screen=CTGY&Category_Code="+cat_code;
	});

	if( $("body#body-store").length ) {
		if (!document.CTGYBack) $("li.pagnation-prev").hide();
		if (!document.CTGYNext) $("li.pagnation-next").hide();
	}

/**
 * Views Slideshow Hacks - dimensions are 610x340px (see global.css for styles)
 */
	function _vss_graft_functions (func1, func2) {
		func1 = func1.toString();
		func2 = func2.toString();
		return func1.substr(0, func1.length-2)+func2.substring(func2.indexOf("{")+1, func2.lastIndexOf("}"))+'}';
	}
	if (Drupal.settings.viewsSlideshowThumbnailHover) {

		// word wrap strong "title" tags so that the padding looks right ...
		$(".view-djs-slideshow .slideshow-overlay strong").each(function(n){
			var i = 0, rows = [''], word, words = $(this).text().split(' ');

			// organize words in rows ...
			while (words.length) {
				// break off word ...
				word = words.shift();
				// row length within max chars with new word then concat
				if (rows[i].length + word.length + 1 < 40) rows[i] = rows[i].concat(' ', word);
				// if not ...
				else {
					// trim current row to finalize ...
					rows[i] = $.trim(rows[i]);
					// use the word to start a new row ...
					rows.push(word);
					// increment row index ...
					i++;
				}
			}
			// trim final row ...
			rows[i] = $.trim(rows[i]);

			// reinsert title in row form ...
			$(this).replaceWith('<strong>'+rows.join('</strong><br/><strong>')+'</strong>');
		});

		// graft new settings into vss settings ...
		for (var id in Drupal.settings.viewsSlideshowThumbnailHover) {
			if (id.indexOf('djs_slideshow') != -1) {
				// get settings ...
				var settings = Drupal.settings.viewsSlideshowThumbnailHover[id];

				// graft new before code into the options ...
				eval("settings.opts.before = "+_vss_graft_functions(settings.opts.before, function(){
					//$('.slideshow-overlay', current).hide();
				}));

				// graft new after code into the options ...
				eval("settings.opts.after = "+_vss_graft_functions(settings.opts.after, function(){
					$('.slideshow-overlay', curr).hide();
					$('.slideshow-overlay', next).css({right:606}).show().animate({right:4}, 'slow');
				}));

				// reinject settings ...
				var context = $(id+" :first").cycle(settings.opts);
			}
		}
	}


/**
 * TopSpin Email Signup ...
 * See: https://docs.topspin.net/tiki-index.php?page=Email+For+Media+REST+API
 */
	$('form#mailinglist')
		.submit(function(e){

			var F = $(this).get(0);
			$.getJSON('/topspin/e4m/'+(F.streetteam_campaign_id.checked ? F.streetteam_campaign_id.value : F.campaign_id.value)+'/'+escape(F.email.value), function(data){
				if (data.success) $('form#mailinglist').replaceWith('<hr/><p style="text-align:center; font-size:120%; font-weight:bold;">Thank you for signing up to our mailing list. You should receive an email shortly.</p>');
				else {
					alert("Please enter a valid email address.");
					F.email.focus();
				}
			});

			// don't submit the form ...
			return false;

		});

/**
 * Parse FB fbml codes ...
 */
	$(".fb").each(function(i){
		FB.XFBML.parse(this);
	});


});


 // Copyright 1999, 2000 by Ray Stott - ver 2.0
 // OK to use on noncommercial sites as long as copyright is included
 // Script is available at http://www.crays.com/jsc

 var popWin = null    // use this when referring to pop-up window
 var winCount = 0
 var winName = "popWinD"
 function openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){

   // global fix of winURL for
   if (winURL == 'http://www.djshadow.com/images/gildansizing.jpg') winWidth = 320;

   var d_winLeft = 20  // default, pixels from screen left to window left
   var d_winTop = 20   // default, pixels from screen top to window top
   winName = "popWinD" + winCount++ //unique name for each pop-up window
   closePopWin()           // close any previously opened pop-up window
   if (openPopWin.arguments.length >= 4)  // any additional features?
     winFeatures = "," + winFeatures
   else
     winFeatures = ""
   if (openPopWin.arguments.length == 6)  // location specified
     winFeatures += getLocation(winWidth, winHeight, winLeft, winTop)
   else
     winFeatures += getLocation(winWidth, winHeight, d_winLeft, d_winTop)
   popWin = window.open(winURL, winName, "width=" + winWidth
            + ",height=" + winHeight + winFeatures)
   }
 function closePopWin(){    // close pop-up window if it is open
   if (navigator.appName != "Microsoft Internet Explorer"
       || parseInt(navigator.appVersion) >=4) //do not close if early IE
     if(popWin != null) if(!popWin.closed) popWin.close()
   }
   function getLocation(winWidth, winHeight, winLeft, winTop){
   return ""
   }

$(document).ready(function() {

if (document.getElementsByName("CMAG_currency")[0]) {
	var currancyForm = document.getElementsByName("CMAG_currency")[0];
	var myindex = currancyForm.selectedIndex;
	var country = currancyForm.options[myindex].text;
	//var country  = Currency.CMAG_currency.selectedIndex.value;
}

$('#bill-cntry-name').html(country);
})

/**
 * TopSpin Shopping Cart Integration
 * See: https://docs.topspin.net/tiki-index.php?page=Purchase+Flow+Callbacks&structure=Dev+Center
 */
TOPSPIN.PurchaseFlow.addListener(function(Cart){
	$('#shopping-cart-itemsCount').text('('+Cart.item_count+')');
}, "CART_UPDATE");



