// =================================================
// = Frogzog. Unified Theme. Merchant Specific JS. =
// =================================================

// req'd js
/* jquery.js, jquery.unified.js, pngfix.js (for ie < 7) */
// req'd css
/* unified.css, unified.merchant.css, unified.merchant_ie.css */

// ajax requests defaults
$.ajaxSetup({ error: function(xml_http_request, text_status, error_thrown) { alert('AJAX error: request failed. (' + text_status + ', ' + xml_http_request.responseText + ').'); } });

// on ready
$(document).ready(function() {
	// apply all merchant unified theme bindings
	fzum_bind();
});

// fzum, apply all bindings
function fzum_bind(context) {
	// apply all unified theme bindings
	fzu_bind(context);
	// panel bindings
	fzum_panelBind(context);
	// push locatoins bindings
	fzum_pushLocationsBind(context);
	// reports specific bindings
	fzum_reportsBind(context);
	// cart specific bindings
	fzum_cartBind(context);
}

// fzum, cart bindings
function fzum_cartBind(context) {
	// promo code form
	$('form.fz_promo_code').submit(function() {
		// ajax request
		$.ajax({ data: 'fz_promo_code='+$(this).find('input[name="fz_promo_code"]').attr('value'), dataType: 'json', success: function(json) {
			if (json.success) {
				$('.total_order').html(json.total_order);
				$('input[name="fz_promo_code"]').attr('value', '');
				$('table.cart').replaceWith(json.cart);
				fzu_inputErrorUnhighlight($('input[name="fz_promo_code"]'));
			}
			else {
				fzu_inputErrorUnhighlight($('input[name="fz_promo_code"]'));
				fzu_inputErrorHighlight($('input[name="fz_promo_code"]'), json.message);
			}
		}, type: 'post', url: $(this).attr('action') });
		// and stop normal submission
		return false;
	});
	// shipping service change
	$('select[name="fz_shipping_service"]').change(function() {
		// if valid shipping service
		if ($(this).attr('value') == '01' || $(this).attr('value') == '02' || $(this).attr('value') == '03')  {
			// submit ajax request to change the zip
			$.ajax({ dataType: 'json', success: function(json) { if (json.success) { $('.total_shipping').html(json.total_shipping); $('.total_order').html(json.total_order); } }, type: 'get', url:  '/merchant/store/set-shipping-service/'+$(this).attr('value') });
		}
	});
	// shipping zip change
	$('input[name="fz_shipping_zip"]').keydown(function(event) {
		// disallow 'enter' submits
		if (event.keyCode == 13) return false;
		// if 5 digit number, set shipping zip
		if (new RegExp(/(^\d{5}$)/).test($(this).attr('value'))) {
			// submit ajax request to change the zip
			$.ajax({ dataType: 'json', success: function(json) { if (json.success) { $('.total_shipping').html(json.total_shipping); $('.total_order').html(json.total_order); } }, type: 'get', url:  '/merchant/store/set-shipping-zip/'+$(this).attr('value') });
		}
	});
	// cart quantity change
	$('input.fz_product_quantity').keyup(function() {
		// filter non numeric out
		$(this).attr('value', $(this).attr('value').replace(/[^0-9]/g, ''));
		// if setting to zero quantity
		if ($(this).attr('value') == '0') {
			fzu_tipShow($(this).siblings('.tip').attr('id'));
		}
		// else update
		else {
			// if tip is shown, hide it
			fzu_tipHide($(this).siblings('.tip').attr('id'));
			// store last keypress for this
			$(this).attr('last_keyup', new Date().getTime());
			// else set timeout for updating quantity
			setTimeout('fzum_cartProductQuantityTimeout("' + $(this).attr('id') + '")', 500);
		}
	});
	// cart, shipping address / billing method new, hide if neccessary
	$('.merchant_add_new.hide_new').hide();
	// cart, shipping address change
	$('select[name="fz_merchant_shipping_address_id"], select[name="fz_merchant_pay_id"]').change(function() {
		// if 'new' show new form
		if ($(this).find('option:selected').attr('value') == 'new') $('.merchant_add_new').slideDown();
		// else hide it
		else $('.merchant_add_new').slideUp();
	});
}

// fzum, set a product quantity
function fzum_cartProductQuantitySet(input_id, quantity) {
	var $input = $('#' + input_id);
	$input.attr('value', quantity);
	fzum_cartProductQuantityUpdate($input);
}

// fzum, product quantity timeout
function fzum_cartProductQuantityTimeout(input_id) {
	// the <input> quantity we're looking at
	var $input = $('#' + input_id);
	// if there hasn't been a keyup in the last bit
	if (parseInt($input.attr('last_keyup')) < (new Date().getTime() - 400)) fzum_cartProductQuantityUpdate($input);
	
}

// fzum, cart product quantity update
function fzum_cartProductQuantityUpdate($input) {
	// dont submit if zero quantity
	if ($input.attr('value') == 0) return;
	// show loading
	$input.closest('tr').find('.product_total_price').html('(Updating)');
	// submit ajax request
	$.ajax({ data: 'merchant_cart_product_id='+$input.attr('rel')+'&product_quantity='+$input.attr('value'), dataType: 'json', success: function(json) {
		if (json.success) {
			var $product_row = $('.fz_product_quantity[rel='+json.product_id+']').closest('tr');
			$product_row.find('.product_total_price').html(json.product_total_price);
			$('.total_quantity').html(json.total_quantity);
			$('.total_price').html(json.total_price);
			$('.total_shipping').html(json.total_shipping);
			$('.total_order').html(json.total_order);
		} }, type: 'post', url: '/merchant/store/update-quantity'
	});
}

// fzum, panel bindings
function fzum_panelBind(context) {
	// for each panel
	$('.panel').each(function() {
		// select an item from a list
		$(this).find('.panel_list_select').click(function() { fzum_panelListSelect($(this).attr('id')); return false; });
		// add/delete a relation
		$(this).find('.panel_relation_select').click(function() { fzum_panelRelationSelect($(this).attr('id')); return false; });
	});
}

// fzum, panel, select item
function fzum_panelListSelect(select_id) {
	// if no selected_id
	if (!select_id || select_id =='0') {
		// hide old data
		$('#panel_details .panel_content').removeClass().addClass('panel_content').html('');
		$('#panel_relations .panel_content').removeClass().addClass('panel_content').html('');
		// and done and done
		return;
	}
	// jquery object of the item to select
	var $item_to_select = $('#' + select_id);
	// if already selected, no nothing
	if ($item_to_select.parents('li').eq(0).hasClass('selected')) return;
	// unselect all the <li>'s
	$item_to_select.parents('.panel_list').find('li').removeClass('selected').find('.icon_12_delete_reverse').removeClass('icon_12_delete_reverse');
	// select the current <li>
	$item_to_select.parents('li').eq(0).addClass('selected').find('.icon_12_delete').addClass('icon_12_delete_reverse');
	// set loading
	fzum_panelLoading('panel_details');
	fzum_panelLoading('panel_relations');
	// submit ajax request
	$.ajax({ dataType: 'json', type: 'GET', url: $item_to_select.attr('href'), success: function(json) { fzum_panelUpdate(json.details); fzum_panelUpdate(json.relations); } });
}

// fzum, set panel to 'loading'
function fzum_panelLoading(panel_id) {
	$('#' + panel_id + ' .panel_content').html('').addClass('loading');
}

// fzum, panel refresh amd optionally select an item
function fzum_panelRefresh(select_id) {
	// id of item to select after refresh
	$('#panel_list').attr('select_id', select_id ? select_id : '0');
	// set loading
	fzum_panelLoading('panel_list');
	// load the new content
	$.ajax({ dataType: 'json', type: 'GET', url: document.location + '/list', success: function(json) { fzum_panelUpdate(json); } });
}

// fzum, panel on relation checkbox mousedown
function fzum_panelRelationSelect(checkbox_id) {
	// the checkbox
	var $checkbox = $('#' + checkbox_id);
	//  url for the AJAX request
	var request_url = $checkbox.attr('checked') ? $('#panel_relation_add_url').attr('value') : $('#panel_relation_delete_url').attr('value');
	// selected list item id
	var list_id = $('#panel_list li.selected a.panel_list_select').attr('value');
	// relation id
	var relation_id = $checkbox.attr('value');
	// disable input checkbox(es)
	fzu_inputDisable(relation_id == 'all' ? $checkbox.closest('.panel_list') : $checkbox.parents().eq(0));
	// submit AJAX request
	$.ajax({
		data: { list_id: list_id, relation_id: relation_id },
		dataType: 'json',
		type: 'POST',
		url: request_url,
		success: function(json) {
			// succesful request
			if (json.success == true) {
				// enable checkboxes
				fzu_inputEnable($('#panel_relations'));
				// adding a relation
				if (json.process == 'relation-add') {
					// check appropriate boxes
					relation_id == 'all' ? $('#panel_relations input[name="relation"]').attr('checked', 'checked') : $checkbox.attr('checked', 'checked');
					// and update the 'select' all and decoy classes
					fzum_panelRelationsUpdate();
				}
				// deleting a relation
				else {
					// uncheck appropriate boxes
					relation_id == 'all' ? $('#panel_relations input[name="relation"]').removeAttr('checked') : $checkbox.removeAttr('checked');
					// and update the 'select' all and decoy classes
					fzum_panelRelationsUpdate();
				}
			}
			// AJAX error
			else alert('Error! ' + json.message);
		}
	});
}

// update the relations
function fzum_panelRelationsUpdate() {
	// are all the checkboxes checked
	var all_checked = true;
	// for each relation checkbox
	$('#panel_relations input[name="relation"]').each(function() {
		if ($(this).attr('checked')) $('#' + $(this).attr('rel')).addClass('input_checkbox_decoy_checked');
		else {
			$('#' + $(this).attr('rel')).removeClass('input_checkbox_decoy_checked');
			all_checked = false;
		}
	});
	// the 'select all' checkbox
	$select_all = $('#relation_id_all');
	// if all checked
	if (all_checked) {
		$select_all.attr('checked', 'checked');
		$('#' + $select_all.attr('rel')).addClass('input_checkbox_decoy_checked');
	}
	// else not all checked
	else {
		$select_all.removeAttr('checked');
		$('#' + $select_all.attr('rel')).removeClass('input_checkbox_decoy_checked');
	}
}

// fzum, update panel
function fzum_panelUpdate(panel_json) {
	/* panel_json has .id, .header_class, .header_html, .content_class, .content_html properties */
	// if no panel_id do nothing
	if (!panel_json.id) return;
	// set classes and html content, remove 'loading' class, and fade in content
	$('#' + panel_json.id).find('.panel_header').removeClass().addClass('panel_header ' + panel_json.header_class).html(panel_json.header_html).siblings('.panel_content').removeClass().addClass('panel_content ' + panel_json.content_class).html(panel_json.content_html).find('*').css('display', 'none').fadeIn(200);
	// and apply bindings to anything we just loaded in
	fzum_bind($('#' + panel_json.id));
	// and select o tron
	if ($('#' + panel_json.id).attr('select_id')) fzum_panelListSelect($('#' + panel_json.id).attr('select_id'));
	$('#' + panel_json.id).attr('select_id', '');
}

// fzum, push location bindings
function fzum_pushLocationsBind(context) {
	// on .push_location checkbox mousedown
	$('.push_location', context).click(function() { fzum_pushLocationsUpdate($(this).attr('id')); });
}

// fzum, push locations update
function fzum_pushLocationsUpdate(checkbox_id) {
	// the checkbox
	var $checkbox = $('#' + checkbox_id);
	//  url for the AJAX request
	var request_url = $('#request_url').attr('value');
	// disable input checkbox
	fzu_inputDisable($checkbox.closest('ul'));
	// array of the selected checkbox values
	var selected = Array();
	// if 'all' was clicked
	// if ($checkbox.attr('value') == 'all' && $checkbox.attr('checked')) $checkbox.parents('form').find('.push_location').each(function() { selected.push($(this).attr('value')); });
	if ($checkbox.attr('value') == 'all') {
		// if 'all' is checked, add every select box to the selected array, and check every .push_location
		if ($checkbox.attr('checked')) $checkbox.closest('form').find('.push_location').each(function() {
			selected.push($(this).attr('value'));
			fzu_inputCheckboxSelect($(this));
		});
		// else 'all' was unchecked, un-check every .push_location
		else $checkbox.closest('form').find('.push_location').each(function() {
			fzu_inputCheckboxUnselect($(this));
		});
	}
	// else normal checkbox was click, get the selected checkboxes
	else $checkbox.parents('form').find('.push_location:checked').each(function() { selected.push($(this).attr('value')); });
	// submit AJAX request
	$.ajax({
		data: { 'fz_push_locations[]': selected },
		dataType: 'json',
		type: 'POST',
		url: request_url,
		success: function(json) {
			// update subscribers / cost
			$('#summary_subscribers').html(json.subscribers);
			$('#summary_cost').html(json.cost);
			// re-enable checkboxes
			fzu_inputEnable($checkbox.closest('ul'));
			// and update 'select all'
			$select_all_checkbox = $checkbox.closest('form').find('.push_location[value="all"]');
			if ($checkbox.closest('form').find('.push_location:not([value="all"]):checked').length == $checkbox.closest('form').find('.push_location:not([value="all"])').length) fzu_inputCheckboxSelect($select_all_checkbox);
			else fzu_inputCheckboxUnselect($select_all_checkbox);
		}
	});
}

// fzum, reports bindings
function fzum_reportsBind(context) {
	// report param binding
	$('.report_param', context).find('select').eq(0).change(function() { fzum_reportsUpdate($(this)); }).each(function() { fzum_reportsUpdate($(this)); });
}

// fzum, reports update
function fzum_reportsUpdate($param_select) {
	// sub parameters
	var $sub_param_input = $('#' + $param_select.attr('name') + '_sub_params_' + $param_select.find('option:selected').attr('value'));
	var sub_params = $sub_param_input.attr('value');
	var sub_param_selected = $sub_param_input.attr('selected');
	// if has sub parameters
	if (sub_params && sub_params != 'none') {
		// the sub parameters select
		$sub_param_select = $param_select.parents('.report_param').eq(0).siblings('.report_sub_param').find('select').eq('0');
		// split into array
		var sub_params_options = sub_params.split(', ');
		// remove old <option>s
		$sub_param_select.html('');
		// set new <option>s
		var options_html = '';
		for (var i=0; i < sub_params_options.length; i++) {
			// db value and display value are pipe separated, param_value[0] = db value, param_value[1] = display value
			param_values = sub_params_options[i].split('|');
			// write the <option>
			options_html += '<option value="' + param_values[0] + '">' + param_values[1] + '</option>';
		}
		// update html
		$sub_param_select.html(options_html);
		// if selected value
		if (sub_param_selected) {
			$sub_param_select.find('option:selected').removeAttr('selected');
			$sub_param_select.find('option[value="' + sub_param_selected + '"]').attr('selected', 'selected');
		}
		// update <select> decoy
		fzu_inputSelectUpdate($sub_param_select);
		// and show it
		$param_select.parents('.report_param').eq(0).siblings('.report_sub_param').find('.wrapper').eq('0').css('display', 'block');
	}
	// else hide the select
	else $param_select.parents('.report_param').eq(0).siblings('.report_sub_param').find('.wrapper').eq('0').css('display', 'none');
}
