/**
 *	redirect to the selected event 
 */
function goSelectedEvent(elem)
{
	
	if(elem.selectedIndex > 0)
	{
		window.location = elem.options[elem.selectedIndex].value;
		//redirectTo(elem.options[elem.selectedIndex].value);
	}else
	{
		alert('Please select an Event.');
	}
	return false;


}


function getNum(str)
{
	
	if(typeof(str) != 'undefined' && str != '')
	{
		var r = str.match(/[\d\.]+/g);	
		if(typeof(r) != 'undefined' &&  r &&  typeof(r[0]) != 'undefined')
		{
			return parseInt(r[0]);
		}		
	}
	return 0;
};
/**
*	redirect to the specified url
*/
function redirectTo(url)
{
	document.location.href = url;
}

String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}

function intVal(str)
{
	
	var num = parseInt(str);
	if(isNaN(num))
	{
		return 0;
	}else
	{
		return num;
	}
}

function floatVal(str)
{
	var num = parseFloat(str);
	if(isNaN(num))
	{
		return 0;
	}else
	{
		return num;
	}	
}

function intVal(str)
{
	var num = parseInt(str);
	if(isNaN(num))
	{
		return 0;
	}else
	{
		return num;
	}
}
function changeEntityTitle(elem)
{
	if(elem.value == 'Others')
	{
		$('#otherTitle').show();
		$('#other_title').val('Please Specify...');
	}else
	{
		$('#otherTitle').hide();
		$('#other_title').val('');
	}
}

function clearEntityTitle(elem)
{
	if(elem.value == 'Please Specify...')
	{
		elem.value = '';
	}
	
}
/**
*	a=>number
*   b=>decimals
*   c=>dec_point
*   d=>thousands_sep
*/
function number_format(a, b, c, d) {
 if(typeof(c) == 'undefined')
 {
 	c = '.';
 }
 if(typeof(d) == 'undefined')
 {
 	d = ',';
 }
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

/*function number_format( number, decimals, dec_point, thousands_sep ) {
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57
 
    var i, j, kw, kd, km;
 
    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ".";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ",";
    }
 
    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
 
    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }
 
    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
 
 
    return km + kw + kd;
}*/


function publicLogout()
{
	document.getElementById('formPublicLogout').submit();
}


function CheckIsIE()
{
	if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER') 
	{ return true;}
	else { return false; }
}


function printIframe(iframeId)
{

if (CheckIsIE() == true)
{
	document.iframeOrder.focus();
	document.iframeOrder.print(); 	
}
else
{
window.frames['iframeOrder'].focus();
window.frames['iframeOrder'].print();
}

}

	function autoTab(original,destination)
	{
		
		if (original.getAttribute&&original.value.length>=original.getAttribute("maxlength"))
		{

	         original.value = original.value.slice(0, original.getAttribute("maxlength"));
	         destination.select();

		}

	}
	
	function printTicketOrder(url)
	{
		var newWin = window.open(url, 'ticketOrder', 'width=600, height=666,resizable, menubar,scrollbars');
		newWin.focus();
	}
	
	function showInfo(info, lineBreak)
	{
		var msgOutput = '';
		if(typeof(lineBreak) == 'undefined')
		{
			var lineBreak = 'line_break';
		}
		var msg = info.split(lineBreak);
		
		for(var i in msg)
		{
			if(msg[i] != '')
			{
				msgOutput += msg[i] + '\n';
			}
		}
		alert(msgOutput);
	}
	
	function shownPurchaseConditions()
	{
	    //window.open('http://www.streamticketing.co.nz/index.php/ps_pagename/ticket_purchase_policy', 'purchase_conditions', 'width=770, height=640, scrollbars=0');

	    //this line has been edited because it was not pointing to the correct location.
	    //window.open('http://www.streamticketing.co.nz/index.php?page=purchase-policy', 'purchase_conditions', 'width=770, height=640, scrollbars=0');
		window.open('https://secure.streamticketing.co.nz/?page=purchase-policy', 'purchase_conditions', 'width=770, height=640, scrollbars=0');
	    
	}
	
/**
*	get the discount for selected qty and ticket class id apply
*/
function getSaleDiscount(ticketClassId, qty)
{
	var discounts = ticketClassDiscounts[ticketClassId];
	for(var i in discounts)
	{

		if(typeof(discounts[i]) == 'object')
		{

			if(qty >= discounts[i].minimum_number)
			{
				return discounts[i].discount;
			}		
		}

	}

	return false;
}

    //Upate the contents inside the cart
	function updateCart()
	{

		var total = 0;
		var subTotal = floatVal($('#normal_booking_fee').val());
		var cartGST = 0;
		var postage = 0;
		var payment = 0;
		var WOP_Booking_Fee = WOP_COST;
		var trasactionCharge = 0;
		var postageCharge = 0;
		
		
		
        $('input.price').each(
			function() {

			    if ($(this).hasClass('ticket')) {

			        var ticketTypeId = getNum(this.id);
			        var price = floatVal(eventTickets[ticketTypeId].price);
			        var qty = floatVal(this.value);
			        var discount = getSaleDiscount(ticketTypeId, qty);

			        if (typeof (discount) != 'boolean') {
			            finalPrice = discount;
			        } else {
			            finalPrice = price;
			        }

			        var subPrice = qty * finalPrice;
			        $('#ticketCost' + ticketTypeId).empty().html('$' + number_format(finalPrice, 2));
			        $('#ticketTotal' + ticketTypeId).empty().html('$' + number_format(subPrice, 2));

			        subTotal += subPrice;	
					
			    } else if ($(this).hasClass('product')) {
				
			        var productId = getNum(this.id);
			        var price = floatVal(products[productId].price);
			        var qty = floatVal(this.value);
			        var finalPrice = price;
			        var subPrice = qty * finalPrice;
					
			        $('#productCost' + productId).empty().html('$' + number_format(100, 2));
			        $('#productTotal' + productId).empty().html('$' + number_format(subPrice, 2));

			        subTotal += subPrice;
					
			    }
			}
		);
		
		if( $("[@name=cart_type]:checked").val() == 'WOP'){
			postageCharge += WOP_Booking_Fee;
			$('#cartBooking').empty().html(number_format(WOP_Booking_Fee, 2));
		}else {
			$('#cartBooking').empty().html(number_format(0, 2));
		}
			
		if( insideFeeEnabled   == 1 && subTotal > 0 ) 
		{
			if ( insideFeeType == CT_STATIC ){
				trasactionCharge = insideFeeAmount;	
			} else if (  insideFeeType == CT_PERCENT ){
				trasactionCharge = insideFeeAmount * subTotal;
			}
		}

		total = subTotal + trasactionCharge + postageCharge;
		
		//Displays the total cost in the web page
		cartGST = (total/(1 + gst) * gst);
		
		$('#cartSubtotal').empty().html(number_format(subTotal, 2));
		$('#cartGST').empty().html(number_format(cartGST, 2));
		$('#cartTotal').empty().html(number_format(total, 2));
		$('#cartInsideFee').empty().html( number_format( trasactionCharge, 2)  );
	}
	
	function chooseCart(cartType)
	{

		if(cartType == "online"){
		
		$('input.WOP').attr('disabled', 'true');
		$('input.WOP').attr('value', '0');
		$('input.online').attr('disabled', '');
		} else {
		
		$('input.WOP').attr('disabled', '');
		$('input.online').attr('disabled', 'true');
		$('input.online').attr('value', '0');
		
		}
		updateCart();
	
	}
	
	function choosePaymentMethod(paymentMethod)
	{
		var isSelected = false;
		$('input.price').each(
			function()
			{
				if(getNum(this.value))
				{
					isSelected = true;
				}
			}
		);
		if(isSelected)
		{
			if(document.getElementById('purchaseConditionsRead').checked)
			{
				document.getElementById('formStep2').submit();	
			}else
			{
				alert('Please ensure you have read and understood the Purchase Conditions.');
			}
			
		}else
		{
			alert('Please enter the quantity of tickets/products you wish to purchase.')
		}
		return false;
	}		  	