// JavaScript Document

// On Load
$(function () {
	$('#state').change(
		function(){
			stateChange();
		}
	);
	
	$('#countryS').change(
		function(){
			countryChange();
		}
	);
});

function stateChange(){
	if($('#state').val() == 'NY' && $('#country').val() == 'US'){
		var subtotal = parseFloat($('#subtotalCheckout').html());
		var tax = subtotal * 0.0875;
		var shipping = parseFloat($('#shippingCheckout').html());
		var total = subtotal + tax + shipping;
		
		$('#taxCheckout').html(sprintf('%01.2f', tax));
		$('#totalCheckout').html(sprintf('%01.2f', total));
		
	} else {
		
		var subtotal = parseFloat($('#subtotalCheckout').html());
		var tax = subtotal * 0.0;
		var shipping = parseFloat($('#shippingCheckout').html());
		var total = subtotal + tax + shipping;
		
		$('#taxCheckout').html(sprintf('%01.2f', tax));
		$('#totalCheckout').html(sprintf('%01.2f', total));
	}
}

function countryChange(){
	if($('#countryS').val() == 'US'){
		var subtotal = parseFloat($('#subtotalCheckout').html());
		
		if($('#state').val() == 'NY'){
			var tax = subtotal * 0.0875;
		} else {
			var tax = subtotal * 0.0;
		}
		
		var shipping = parseFloat($('#shippingCheckout').html());
		
		if(shipping != 0){
			shipping = 16.95;
	
			if(subtotal < 200){ shipping = 14.95; }
			if(subtotal < 150){ shipping = 11.95; }
			if(subtotal < 100){ shipping = 8.95; }
			if(subtotal < 50){ shipping = 6.95; }
			if(subtotal < 25){ shipping = 4.95; }
		}
		
		var total = subtotal + tax + shipping;
		
		$('#taxCheckout').html(sprintf('%01.2f', tax));
		$('#shippingCheckout').html(sprintf('%01.2f', shipping));
		$('#totalCheckout').html(sprintf('%01.2f', total));
		
	} else {
		
		var subtotal = parseFloat($('#subtotalCheckout').html());
		var tax = subtotal * 0.0;
		var shipping = parseFloat($('#shippingCheckout').html());
		
		if(shipping != 0){
			shipping = 16.95;
	
			if(subtotal < 200){ shipping = 14.95; }
			if(subtotal < 150){ shipping = 11.95; }
			if(subtotal < 100){ shipping = 8.95; }
			if(subtotal < 50){ shipping = 6.95; }
			if(subtotal < 25){ shipping = 4.95; }
			
			if($('#countryS').val() == 'CA'){
				shipping = shipping + 3;
			}else if($('#countryS').val() == 'AU' || $('#countryS').val() == 'JP' || $('#countryS').val() == 'GB' || $('#countryS').val() == 'IE'){
				shipping = shipping + 5;
			}else{
				shipping = shipping + 10;
			}
		}
		
		var total = subtotal + tax + shipping;
		
		$('#taxCheckout').html(sprintf('%01.2f', tax));
		$('#shippingCheckout').html(sprintf('%01.2f', shipping));
		$('#totalCheckout').html(sprintf('%01.2f', total));
	}
}

// Translate
try {
	$.translate().ready(function(){ 
		startTranslate();
	});
} catch(e){
	//
}

function switchLang(newLang){
	$.get('ajax.php', {'lang':newLang}, function(){
		if(lang == 'en'){
			lang = newLang;
			startTranslate();
		}else{
			window.location.reload();
		}
	});
}

function startTranslate(){
	if(lang != 'en'){
		$('#mainContent').translate('en',lang, {

                                start:          function() {  $('#translateOverlayID').show(); },

                                complete:    	function() {	$('#translateOverlayID').hide(); },

                                error:         	function() {  $('#translateOverlayID').hide(); }

                        });
	}
}

// Hide Div
function hide(id) {
	$("#" + id).hide();
}

// 
function showAlbum(artistID, albumID){
	$('#overBg').show();
	$('#overPage').slideUp('slow').empty().load('pages/albumStore.php?select='+artistID+'&data='+albumID, {}, function callback() {$('#overPage').slideDown('slow');});
}

function showMerch(merchID){
	$('#overBg').show();
	$('#overPage').slideUp('slow').empty().load('pages/merchandiseStore.php?data='+merchID, {}, function callback() {$('#overPage').slideDown('slow');});
}

function showVenue(venueID, venueTitleJS, venueLocationJS, venueLocationBR){
	$('#overBg').show();
	$('#overPage').slideUp('slow').empty().load('pages/venue.php?data='+venueID,{}, function callback() {$('#overPage').slideDown('slow');loadMap(venueTitleJS, venueLocationJS, venueLocationBR);});
}

function artistAlbum(artistID, albumID){
	$('#albumDetails').fadeOut('slow').load('pages/album.php?select='+artistID+'&data='+albumID,{}, function callback(){$('#albumDetails').fadeIn('slow');});
}

// Shopping Cart
function cartAdd(sel,data,type){
	$('#overBg').show();
	$('#overPage').slideUp('slow').empty().load('./pages/cart.php?select='+sel+'&data='+data+'&action=add&type='+type,{}, function callback() {$('#overPage').slideDown('slow');$('#cartNav').load('./pages/cartNavStore.php');});
}

function cartDelete(cartID){
	$('#overBg').show();
	$('#overPage').slideUp('slow').empty().load('./pages/cart.php?data='+cartID+'&action=remove',{},function callback() {$('#overPage').slideDown('slow');$('#cartNav').load('./pages/cartNavStore.php');});	
}

function cartUpdate(){
	$('#overBg').show();
	$('#shoppingCart').ajaxForm({ 
        target: '#overPage', 
        success: function() { 
            $('#overPage').slideDown('slow');
			$('#cartNav').load('./pages/cartNavStore.php');
        } 
    });
	
	$('#shoppingCart').submit();
}

function useBillingShipping(){
	$('#firstNameS').val($('#firstName').val());
	$('#lastNameS').val($('#lastName').val());
	$('#address1S').val($('#address1').val());
	$('#address2S').val($('#address2').val());
	$('#cityS').val($('#city').val());
	$('#stateS').val($('#state').val());
	$('#zipCodeS').val($('#zipCode').val());
	$('#countryS').val($('#country').val());
	stateChange();
	countryChange();
}

function useBillingDownload(){
	$('#emailD').val($('#email').val());
}

// Flash Player Controls
var previewAudio;
var currentID;
var flashReady = false;

function callJS(){
	flashReady = true;
}

function songClick(thisID, songPath){

	if(flashReady == true){
		
		if(navigator.appName.indexOf("Microsoft") != -1) {
			var previewAudio = window.document['previewAudio'];
		} else {
			var previewAudio = document['previewAudio'];
		}
		
		
		if(thisID == currentID){
			songStop();
			previewAudio.remoteStop();
			currentID = '';
		} else {
			if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))){
				location.href = '/' + songPath;
			} else {
				if(currentID){
					songStop();
				}
				previewAudio.remotePlay(songPath);
				songPlay(thisID);
				currentID = thisID;
			}
		}
		
	}
}

function songStop(){ 
	$("#" + currentID).html('<img src="images/play.gif" alt="play" />');
}

function songPlay(thisID){ 
	$("#" + thisID).html('<img src="images/loading.gif" alt="loading" />');
}

function songBufferComplete(){
	$("#" + currentID).html('<img src="images/pause.gif" alt="pause" />');
}

// Google Maps
var map = null;
var geocoder = null;

function loadMap(sName, sTaddress, sFaddress) {
	if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("goodcharamelMap"));

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());

        geocoder = new GClientGeocoder();

		var sTdirections = 'http://www.google.com/maps?f=d&hl=en&saddr=' + '' + '&daddr=' + sTaddress;
		var sFdirections = 'http://www.google.com/maps?f=d&hl=en&saddr=' + sTaddress + '&daddr=';
		
		var sTinfo = '<div style="text-align: left;">' + sName + '<br>' + sFaddress + '<br><br>Get directions: <a href="' + sTdirections + '">To here</a> - <a href="' + sFdirections + '">From here</a><br><br></div>';

		showAddress(sTaddress, sTinfo);
	}
}

function showAddress(address, info) {
	if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
              map.setCenter(point, 15);
              var marker = new GMarker(point);
              map.addOverlay(marker);
              marker.openInfoWindowHtml(info);
            }
          }
        );
	}
}


/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}
