// JavaScript Document
$(document).ready(function() {					 
	initSportSelect();
	initSelectBoxType();
	st_step_3 = 0;
	st_step_4 = 0;
	sm_step_3 = 0;
	sm_step_4 = 0;
	ml_step_3 = 0;
	ml_step_4 = 0;
	tm_step_4 = 0;
	min_width = 250;
	
	
	initPreviewSave();
	initPreview();
	initBoxDelete();
	league_add_remove_init();
	sm_market_add_remove_init();
	tm_market_add_remove_init();
	initFontFamilyAndSize();
	initCodePopup();
	
	

	$('a.box_preview_cancel').click(function(e){
		e.preventDefault();
		$('.bookie_holder').fadeOut('fast');
	});
	
	$('.settings_row').click(function() {
		var sample_div = $('.sample', this);
	 	sample_id = '#' + sample_div.attr('id');
	 	input_id = sample_id.replace('_sample', '_input');
		current_color = $(input_id).val();
	}).ColorPicker({
		color: '0099FF',
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(current_color);
		},
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).ColorPickerHide();
		},
		onShow: function (colpkr) {
			$(colpkr).show();
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).hide();
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			$(sample_id).css('backgroundColor', '#' + hex);
			$(input_id).val(hex);
			
			updateBoxItems(input_id, hex);
	
		}
	}).bind('keyup', function(e){
		var hex = $(input_id).val();
		$(this).ColorPickerSetColor(hex);
		$(sample_id).css('backgroundColor', '#' + hex);
		updateBoxItems(input_id, hex);
		
		if(e.keyCode == 13 || e.keyCode == 27) { // enter or esc
			$('.colorpicker').hide();
		}
	});

	
	$('input#show_box_title').change(function () {
    if($(this).attr("checked") === true) {
			$('.box_title_details, .affbox_title').show();
        //return;
    }
    else {
			$('.box_title_details, .affbox_title').hide();
		}
	});
	
	$('input#show_market_title').change(function () {
    if($(this).attr("checked") === true) {
			$('.market_title_details, .affbox_market_name').show();
        //return;
    }
    else {
			$('.market_title_details, .affbox_market_name').hide();
		}
	});

	$('.save_new_style_link_a').click(function(e) {
		e.preventDefault();
		saveBoxStyle();
	});
	
	
	$('#box_styles_selector').change(function() {
		var style_id = $('#box_styles_selector :selected').val();
		updateDataWithCurrentSelectedStyle(style_id);
	});
	
	$('#odds_table_odds_format').change(function() {
		updateOddsFormat();
	});
	
	
	
}).bind('keyup', function(e){
		if(e.keyCode == 13 || e.keyCode == 27) { // enter or esc
			$('.colorpicker').hide();
			if(e.keyCode == 27) {
				$('.bookie_holder').hide();
			}
		}
});




/************ FUNCTIONS ****************/

function updateOddsFormat() {
	var format = $('#odds_table_odds_format').val();
	$('.affbox_odds span.selected').removeClass('selected');
	if(format == 'f') {
		$('span.fra').addClass('selected');
	}
	else if(format == 'a') {
		$('span.ame').addClass('selected');
	}
	else {
		$('span.dec').addClass('selected');
	}
}

function updateDataWithCurrentSelectedStyle(style_id) {

	//if(style_id != null && box_styles["style_" + style_id] != null) {
		var style_key = 'style_' + style_id;
		var style = box_styles[style_key];
		var str = '';
		var hex_regexp = /^[a-f0-9]{6}$/gi;
		for(key in style){
			var val = style[key];
			val = val.replace('"', '&quot;');
			//alert(key + ' -- ' + val);
			if(val.match(hex_regexp)) {
				var input_id = '#' + key + '_input';
				var sample_id = input_id.replace('_input', '_sample');
				$(sample_id).css('backgroundColor', '#' + val);
				$(input_id).val(val);
				updateBoxItems(input_id, val);
			}
			else {
				$('#' + key).val(style[key]);
				updateOddsFormat();
				
				if(key == 'show_box_title') {
					if(val == 0) {
						$('.affbox_title').css('display', 'none');
						$('#show_box_title').attr('checked', false);
						$('.box_title_details').css('display', 'none');
					}
					else {
						$('.affbox_title').css('display', 'block');
						$('#show_box_title').attr('checked', true);
						$('.box_title_details').css('display', 'block');
					}
				}
				if(key == 'box_title_font_family') {
					var fam = $('#' + key + ' :selected').text();
					$('.affbox_title').css('fontFamily', fam);
				}
				else if(key == 'box_title_font_size') {
					$('.affbox_title').css('fontSize', val);
				}
				
				if(key == 'show_market_title') {
					if(val == 0) {
						$('.affbox_market_name').css('display', 'none');
						$('#show_market_title').attr('checked', false);
						$('.market_title_details').css('display', 'none');
					}
					else {
						$('.affbox_market_name').css('display', 'block');
						$('#show_market_title').attr('checked', true);
						$('.market_title_details').css('display', 'block');
					}
				}
				else if(key == 'market_title_font_family') {
					var fam = $('#' + key + ' :selected').text();
					$('.affbox_market_name').css('fontFamily', fam);
				}
				else if(key == 'market_title_font_size') {
					$('.affbox_market_name').css('fontSize', val);
				}
				
				else if(key == 'odds_table_font_family') {
					var fam = $('#' + key + ' :selected').text();
					$('.affbox_table tr th, .affbox_table tr td').css('fontFamily', fam);
				}
				else if(key == 'odds_table_font_size') {
					$('.affbox_table tr th, .affbox_table tr td').css('fontSize', val);
				}
			}
		}
//}

}

function saveBoxStyle() {
	var err = 0;
	var color_err = 0;
	var bad_colors = '';
	var bad_things = '';
	var alert_text = '';
	var values = new Object();
	values.box_border_color = $('#box_border_color_input').val();
	if(!testHex(values.box_border_color)) {
		color_err++;
		bad_colors += "- Box Border Color\n";
	}
	
	values.box_background_color = $('#box_background_color_input').val();
	if(!testHex(values.box_background_color)) {
		color_err++;
		bad_colors += "- Box Background Color\n";
	}
	
	
	if($('input#show_box_title').attr('checked') === true) {
		values.show_box_title = 1;
	}
	else {
		values.show_box_title = 0;
	}
	
	values.box_title_color = $('#box_title_color_input').val();
	if(values.show_box_title == 1 && !testHex(values.box_title_color)) {
		color_err++;
		bad_colors += "- Box Title Color\n";
	}
	
	values.box_title_background_color = $('#box_title_background_color_input').val();
	if(values.show_box_title == 1 && !testHex(values.box_title_background_color)) {
		color_err++;
		bad_colors += "- Box Title Background Color\n";
	}
	
	
	if($('input#show_market_title').attr('checked') === true) {
		values.show_market_title = 1;
	}
	else {
		values.show_market_title = 0;
	}
	
	values.market_title_color = $('#market_title_color_input').val();
	if(values.show_market_title == 1 && !testHex(values.market_title_color)) {
		color_err++;
		bad_colors += "- Market Title Color\n";
	}
	
	values.market_title_background_color = $('#market_title_background_color_input').val();
	if(values.show_market_title == 1 && !testHex(values.market_title_background_color)) {
		color_err++;
		bad_colors += "- Market Title Background Color\n";
	}
	
	values.odds_table_head_color = $('#odds_table_head_color_input').val();
	if(!testHex(values.odds_table_head_color)) {
		color_err++;
		bad_colors += "- Odds Table Head Color\n";
	}
	
	values.odds_table_head_background_color = $('#odds_table_head_background_color_input').val();
	if(!testHex(values.odds_table_head_background_color)) {
		color_err++;
		bad_colors += "- Odds Table Head Background Color\n";
	}
	
	values.odd_row_color = $('#odd_row_color_input').val();
	if(!testHex(values.odd_row_color)) {
		color_err++;
		bad_colors += "- Odd Row Color\n";
	}
	
	values.odd_row_background_color = $('#odd_row_background_color_input').val();
	if(!testHex(values.odd_row_background_color)) {
		color_err++;
		bad_colors += "- Odd Row Background Color\n";
	}
	
	values.even_row_color = $('#even_row_color_input').val();
	if(!testHex(values.even_row_color)) {
		color_err++;
		bad_colors += "- Even Row Color\n";
	}
	
	values.even_row_background_color = $('#even_row_background_color_input').val();
	if(!testHex(values.even_row_background_color)) {
		color_err++;
		bad_colors += "- Even Row Background Color\n";
	}

	if(color_err > 0) {
		alert_text += "All color inputs must be 6 characters long\nAllowed characters: A-F, 0-9\nPlease check:\n" + bad_colors + "\n";
	}
	
	values.new_style_name = $('#new_style_name').val();
	var regexp = /(^[\s\n]+|[\s\n]+$)/g;
	values.new_style_name = values.new_style_name.replace(regexp, '');
	$('#new_style_name').val(values.new_style_name);
	if(!testCorrectName(values.new_style_name)) {
		alert_text += "The new style name is incorrect\n";
	}
	
	values.selected_style_id = $('#box_styles_selector :selected').val();
	values.selected_style_name = $('#box_styles_selector :selected').text();

	var selected_optgroup = $('#box_styles_selector').find(":selected").parent().attr("label");
	if(selected_optgroup == 'Predefined Styles' && values.new_style_name == '') {
		alert_text += "You cannot save a Predefined Style!\nPlease enter a name for this style to save it as a Custom Style\n";
	}
	
	values.box_title_font_family = $('#box_title_font_family').val();
	values.box_title_font_size = $('#box_title_font_size').val();
	
	values.market_title_font_family = $('#market_title_font_family').val();
	values.market_title_font_size = $('#market_title_font_size').val();
	
	values.odds_table_font_family = $('#odds_table_font_family').val();
	values.odds_table_font_size = $('#odds_table_font_size').val();
	
	values.odds_table_odds_format = $('#odds_table_odds_format').val();
	
	if(alert_text != '') {
		alert(alert_text);
	}
	else {
		var x = 0;
		var values_str = '';
		$.each(values, function(i, n) {
			if(x > 0) {
				values_str += '&';
			}
			values_str += 'v[' + i + ']' + '=' + n;
			x++;
		});

		$.ajax({
			 type: "POST",
			 url: base_url + "styling/",
			 data: "action=save_style&" + values_str,
			 async: false,
			 success: function(msg){
				 if(msg != 1 && msg != 0) {
						$('#ajax_response_holder').append(msg);
						if(new_style_id != null) {
							var new_style_option = '<option value="' + new_style_id + '">' + $('#new_style_name').val() + '</option>';
							$('#box_styles_selector optgroup:nth-child(2)').append(new_style_option);
							$('#box_styles_selector').val(new_style_id);
						}
						$('#new_style_name').val('');
						alert("SUCCESS!\nThe new style was saved!");
				 }
				 else if(msg == 1) {
					 $('#new_style_name').val('');
					 alert("SUCCESS!\nThe style was saved!");
				 }
				 else {
					alert("FAILED! There was an error saving the style!\nPlease try again!");
				 }
			 },
			 error:function() {
				alert("ERROR! There was an error saving the style!\nPlease try again!");
			 }
		 });
	}
	
}

function testHex(str) {
	var regexp = /^[a-f0-9]{6}$/gi;
	if(str.match(regexp)) {
		return true;
	}
	return false;
}

function testCorrectName(str) {
	var regexp = /^(|[a-z0-9]+?[a-z0-9 -]*)$/gi;
	if(str.match(regexp)) {
		return true;
	}
	return false;
}

function initFontFamilyAndSize() {
	// box title
	$('#box_title_font_family').change(function() {
		var fam = $(':selected', this).text();
		$('.affbox_title').css('fontFamily', fam);
	});
	$('#box_title_font_size').change(function() {
		var sz = $(this).val();
		$('.affbox_title').css('fontSize', sz);
	});
	
	
	// market title
	$('#market_title_font_family').change(function() {
		var fam = $(':selected', this).text();
		$('.affbox_market_name').css('fontFamily', fam);
	});
	$('#market_title_font_size').change(function() {
		var sz = $(this).val();
		$('.affbox_market_name').css('fontSize', sz);
	});
	
	// odds table 
	$('#odds_table_font_family').change(function() {
		var fam = $(':selected', this).text();
		$('.affbox_table tr th, .affbox_table tr td').css('fontFamily', fam);
	});
	$('#odds_table_font_size').change(function() {
		var sz = $(this).val();
		$('.affbox_table tr th, .affbox_table tr td').css('fontSize', sz);
	});
}

function updateBoxItems(input_id, hex) {
	// box
	if(input_id == '#box_border_color_input') {
		$('.affbox_inner_div').css('borderColor', '#' + hex);
	}
	if(input_id == '#box_background_color_input') {
		$('.affbox_inner_div').css('backgroundColor', '#' + hex);
	}
	
	// box title
	if(input_id == '#box_title_color_input') {
		$('.affbox_title').css('color', '#' + hex);
	}
	else if(input_id == '#box_title_background_color_input') {
		$('.affbox_title').css('backgroundColor', '#' + hex);
	}
	
	// market title
	if(input_id == '#market_title_color_input') {
		$('.affbox_market_name').css('color', '#' + hex);
	}
	else if(input_id == '#market_title_background_color_input') {
		$('.affbox_market_name').css('backgroundColor', '#' + hex);
	}
	
	// odds table head
	if(input_id == '#odds_table_head_color_input') {
		$('.affbox_odds_table_head th').css('color', '#' + hex);
	}
	else if(input_id == '#odds_table_head_background_color_input') {
		$('.affbox_odds_table_head th').css('backgroundColor', '#' + hex);
	}
	
	// odd rows
	if(input_id == '#odd_row_color_input') {
		$('.affbox_odd td').css('color', '#' + hex);
	}
	else if(input_id == '#odd_row_background_color_input') {
		$('.affbox_odd td').css('backgroundColor', '#' + hex);
	}
	
	// even rows
	if(input_id == '#even_row_color_input') {
		$('.affbox_even td').css('color', '#' + hex);
	}
	else if(input_id == '#even_row_background_color_input') {
		$('.affbox_even td').css('backgroundColor', '#' + hex);
	}
}




function initCodePopup() {
	$('a.box_code_a').click(function(e) {
		var cls = $(this).attr('class').split(' ');
		var info = cls[2].split('_');
		var code = generateBoxCode(info[3], info[1]);
		popup_box_code(code);
	});
}

function generateBoxCode(affkey, boxid) {
	var box_script = '<script type="text/javascript">affkey="' + affkey + '";boxid=' + boxid + ';</script><script type="text/javascript" src="' + base_url + 'scripts/unit-serve.php"></script>';
	return box_script;
}

function popup_box_code(box_code) {
	var html = '<div class="generated_code"><textarea name="generated_code_area" class="generated_code_area">' + box_code + '</textarea><p style="margin-bottom:2px; padding-bottom:2px;">Copy the code in the box and paste it inside your page, where you want the odds box to appear!</div>';
	$('.box_preview_holder').html(html);
	$('.bookie_holder').fadeIn('fast');

}

function popup_box_preview(html) {
	$('.box_preview_holder').html(html);
	$('.bookie_holder').fadeIn('fast');
	
}

function initPreview() {
	$('.preview_link_id').click(function(e){
		e.preventDefault();
		var cls = $(this).attr('class');
		var parts = cls.split(' ');
		var box_id = parts[2].replace('id_','');

		if(box_id > 0) {
			$.ajax({
			 type: "POST",
			 url: base_url + "odds-boxes/ajax/",
			 data: "action=preview" + "&box_id=" + box_id,
			 async: false,
			 success: function(html){
				 popup_box_preview(html);	
			 }
		 });
		}
		
	});
	
}

function initBoxDelete() {
	$('.box_rem').click(function(e){
		e.preventDefault();
		var cls = $(this).attr('class');
		var parts = cls.split(' ');
		var box_id = parts[1].replace('box_rem_','');

		if(box_id > 0) {
			var tr = $(this).parents('tr');
			tr.addClass('prep_for_delete');
			if(confirm('Are you sure you want to delete this Odds Box?')) {
				$.ajax({
				 type: "POST",
				 url: base_url + "odds-boxes/ajax/",
				 data: "action=delete" + "&box_id=" + box_id,
				 async: false,
				 success: function(msg){
					 if(msg == 'OK') {
						 tr.remove();
						 alert('Selected Odds Box has been deleted!');
					 }
					 else {
						 tr.removeClass('prep_for_delete');
						 alert('ERROR! There was an error deleting the selected Odds Box. Please try again later!');
					 }
				 },
				 error: function(){
					 alert('ERROR! There was an error deleting the selected Odds Box. Please try again later!');
				 }
			 });
			}
			else {
				tr.removeClass('prep_for_delete');
			}
		}
		
	});
	
}

function initPreviewSave() {
	$('.preview_link_a, .save_link_a').click(function(e){
		e.preventDefault();
		
		var opp = $(this).attr('class').replace('_link_a', '');
		
		var values_str = checkBoxData();
		if(values_str != false && values_str != null) {
			$.ajax({
			 type: "POST",
			 url: base_url + "odds-boxes/ajax/",
			 data: "action=preview_save_box&opp=" + opp + "&" + values_str + "&box_id=" + box_id,
			 async: false,
			 success: function(html){		
				 if(opp == 'save') {
					window.location = base_url + 'odds-boxes/'; 
				 }
				 else {
					 popup_box_preview(html);	
				 }
			 }
		 });
		}
		
	});
}

function league_add_remove_init() {
	// add league
	$('tr.add_league_tr').live("click", function(){
		var id = $(this).attr('class').replace('add_league_tr am_tr_', '');
		var name = $('td.league_name', this).text();
		var tr = buildSelectedLeagueRow(id, name);
		$('table.l_select_left_table').append(tr);
		$(this).remove();
		
		if(box_league_str == null || box_league_str == '') {
			box_league_str += '.' + id + '.';
		}
		else {
			box_league_str += id + '.';
		}	

	});
	
	//remove league
	$('td.rem_league').live("click", function(){
		var id = $(this).attr('class').replace('rem_league rem_l_', '');
		var name = $('td.league_name', $(this).parent()).text();
		var tr = buildAvailableLeagueRow(id, name);
		$('table.l_select_right_table').append(tr);
		$(this).parent().remove();
		box_league_str = box_league_str.replace('.' + id + '.', '.');

	});
	
	// close leagues pannel
	$('.leagues_select_done').live("click", function(){
		$('.l_selector_shaddow').fadeOut('fast');
		if(ml_step_4 == 0) {
			$('div.ml_step_4').fadeIn('fast');
			ml_step_4 = 1;
		}
	});
	
	// open leagues pannel
	$('.ml_leagues_input').click(function(e){
		e.preventDefault();
		$('.l_selector_shaddow').fadeIn('fast');
	})
}

function sm_market_add_remove_init() {
	
	// add sm market
	$('.m_select_right_table tr.add_market_tr').live("click", function(){
		var id = $(this).attr('class').replace('add_market_tr am_tr_', '');
		var name = $('td.market_name', this).text();
		var tr = buildSelectedMarketRow(id, name);
		$('table.m_select_left_table').append(tr);
		$(this).remove();
		
		if(box_market_str == null || box_market_str == '') {
			box_market_str += '.' + id + '.';
		}
		else {
			box_market_str += id + '.';
		}	
		var mi = $('.sm_markets_input');
		var mi_val = mi.val();
		if(mi_val == '') {
			mi_val += name;
		}
		else {
			mi_val += ', ' + name;
		}
		mi.attr('value', mi_val);
	});
	
	//remove sm market
	$('.m_select_left_table td.rem_market').live("click", function(){
		var id = $(this).attr('class').replace('rem_market rem_m_', '');
		var name = $('td.market_name', $(this).parent()).text();
		var tr = buildAvailableMarketRow(id, name);
		$('table.m_select_right_table').append(tr);
		$(this).parent().remove();
		box_market_str = box_market_str.replace('.' + id + '.', '.');
		
		var mi = $('.sm_markets_input');
		var mi_val = mi.val();
		mi_val = mi_val.replace(', ' + name, '').replace(name + ', ', '').replace(name, '');
		mi.attr('value', mi_val);
	});
	
	// close market pannel
	$('.markets_select_done').live("click", function(){
		$('.m_selector_shaddow').fadeOut('fast');
		if(sm_step_4 == 0) {
			$('div.sm_step_4').fadeIn('fast');
			sm_step_4 = 1;
		}
	});	
	
	// open markets pannel
	$('.sm_markets_input').click(function(e){
		e.preventDefault();
		$('.m_selector_shaddow').fadeIn('fast');
	}).keypress(function(e){
		e.preventDefault();
	});
	
}

function tm_market_add_remove_init() {
	// add tm market
	$('.tm_select_right_table tr.add_market_tr').live("click", function(){
		var id = $(this).attr('class').replace('add_market_tr am_tr_', '');
		var name = $('td.market_name', this).text();
		var tr = buildSelectedMarketRow(id, name);
		$('table.tm_select_left_table').append(tr);
		$(this).remove();
		
		if(box_market_str == null || box_market_str == '') {
			box_market_str += '.' + id + '.';
		}
		else {
			box_market_str += id + '.';
		}	
		var tmi = $('.tm_markets_input');
		var tmi_val = tmi.val();
		if(tmi_val == '') {
			tmi_val += name;
		}
		else {
			tmi_val += ', ' + name;
		}
		tmi.attr('value', tmi_val);
	});
	
	//remove tm market
	$('.tm_select_left_table td.rem_market').live("click", function(){
		var id = $(this).attr('class').replace('rem_market rem_m_', '');
		var name = $('td.market_name', $(this).parent()).text();
		var tr = buildAvailableMarketRow(id, name);
		$('table.tm_select_right_table').append(tr);
		$(this).parent().remove();
		box_market_str = box_market_str.replace('.' + id + '.', '.');
		
		var tmi = $('.tm_markets_input');
		var tmi_val = tmi.val();
		tmi_val = tmi_val.replace(', ' + name, '').replace(name + ', ', '').replace(name, '');
		tmi.attr('value', tmi_val);
	});
	
	// close tm market pannel
	$('.tm_selector_container .markets_select_done').live("click", function(){
		$('.tm_selector_shaddow').fadeOut('fast');
		if(tm_step_4 == 0) {
			$('div.tm_step_4').fadeIn('fast');
			tm_step_4 = 1;
		}
	});
	
	// open team match markets pannel
	$('.tm_markets_input').click(function(e){
		e.preventDefault();
		if($('#tm_box_sport').val() == null || $('#tm_box_sport').val() == 0) {
			alert('You must select a sport first!');
		}
		else {
			$('.tm_selector_shaddow').fadeIn('fast');
		}
	}).keypress(function(e){
		e.preventDefault();
	});
	
}


function buildSelectedLeagueRow(id, name) {
	var tr = '<tr>';
	tr += '<td class="draggable"><span>&nbsp;</span></td>';
	tr += '<td class="league_name">' + name + '</td><td class="rem_league rem_l_' + id + '"><span>&nbsp;</span></td></tr>';
	return tr;
}

function buildAvailableLeagueRow(id, name) {
	var tr = '<tr class="add_league_tr am_tr_' + id + '"><td class="add_league"><span>&nbsp;</span></td><td class="league_name">' + name + '</td></tr>';
	return tr;
}


function buildSelectedMarketRow(id, name) {
	var tr = '<tr><td class="draggable"><span>&nbsp;</span></td><td class="market_name">' + name + '</td><td class="rem_market rem_m_' + id + '"><span>&nbsp;</span></td></tr>';
	return tr;
}

function buildAvailableMarketRow(id, name) {
	var tr = '<tr class="add_market_tr am_tr_' + id + '"><td class="add_market"><span>&nbsp;</span></td><td class="market_name">' + name + '</td></tr>';
	return tr;
}

function checkBoxData() {
	var err = new Array();
	var values = new Object();
	
	var err_count = 0;
	var box_name = $('#box_name').val();
	if (box_name == null || box_name == '') {
		err[err_count] = 'You must input a name for the odds box';
		err_count++;
	}
	else {
		values.bn = box_name;
	}
	
	var box_type = $('#box_type').val();
	if(box_type != 'st' && box_type != 'sm' && box_type != 'ml' && box_type != 'dr' && box_type != 'tb' && box_type != 'tm') {
		err[err_count] = 'You must select a box type';
		err_count++;
	}
	else {
		values.bt = box_type;
	}
	
	if(	box_type == 'st' || box_type == 'sm' || box_type == 'ml' || box_type == 'dr' || box_type == 'tb' || box_type == 'tm') {
		if(box_type == 'st') {
		
			var box_sport = $('#st_box_sport').val();
			if(box_sport == null || box_sport == 0) {
				err[err_count] = 'You must select a sport';
				err_count++;
			}
			else {
				values.bs = box_sport;
			}
			
			var box_category = $('#st_box_category').val();
			if(box_category == null || box_category == 0) {
				err[err_count] = 'You must select a category';
				err_count++;
			}
			else {
				values.bc = box_category;
			}
			
			var box_league = $('#st_box_league').val();
			if(box_league == null || box_league == 0) {
				err[err_count] = 'You must select a league';
				err_count++;
			}
			else {
				values.bl = box_league;
			}
			
			var box_event = $('#st_box_event').val();
			if(box_event == null || box_event == 0) {
				err[err_count] = 'You must select a tournament/race';
				err_count++;
			}
			else {
				values.be = box_event;
			}
	
			var box_market = $('#st_box_market').val();
			if(box_market == null || box_market == 0) {
				var ec = err_count - 1;
					err[err_count] = 'You must select a market';
					err_count++;
			} 
			else {
				values.bm = box_market;
			}
			
			var box_outcomes_nr = $('#st_box_outcomes_nr').val();
			if(box_outcomes_nr == null || box_outcomes_nr == 0) {
				err[err_count] = 'You must select a number of outcomes to show';
				err_count++;
			}
			else {
				values.bon = box_outcomes_nr;
			}
			
			var box_style = $('#st_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
			
			var box_alternate_options = $('#st_box_alternate_options').val();
			values.bao = box_alternate_options;
			
		}
		
		
		else if(box_type == 'sm') {
			var box_sport = $('#sm_box_sport').val();
			if(box_sport == null || box_sport == 0) {
				err[err_count] = 'You must select a sport';
				err_count++;
			}
			else {
				values.bs = box_sport;
			}
			
			var box_category = $('#sm_box_category').val();
			if(box_category == null || box_category == 0) {
				err[err_count] = 'You must select a category';
				err_count++;
			}
			else {
				values.bc = box_category;
			}
			
			var box_league = $('#sm_box_league').val();
			if(box_league == null || box_league == 0) {
				err[err_count] = 'You must select a league';
				err_count++;
			}
			else {
				values.bl = box_league;
			}
			
			var ev_error = 0;
			var box_event = $('#sm_box_event').val();
			if(box_event == null || box_event == 0) {
				err[err_count] = 'You must select a match';
				err_count++;
				ev_error++;
			}
			else {
				values.be = box_event;
			}

			if(box_market_str == null || box_market_str == '' || box_market_str == '.') {
				var ec = err_count - 1;
				err[err_count] = 'You must select a market';
				err_count++;
			}
			else {
				values.bm = box_market_str.replace(/(^\.|\.$)/g, '');
				//alert(values.bm);
			}
			
			var box_outcomes_nr = $('#sm_box_outcomes_nr').val();
			if(box_outcomes_nr == null || box_outcomes_nr == 0) {
				err[err_count] = 'You must select a number of outcomes to show';
				err_count++;
			}
			else {
				values.bon = box_outcomes_nr;
			}
			
			
			var box_style = $('#sm_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
			
			var box_alternate_options = $('#sm_box_alternate_options').val();
			values.bao = box_alternate_options;
		}
		
		else if(box_type == 'ml') {
			var box_sport = $('#ml_box_sport').val();
			if(box_sport == null || box_sport == 0) {
				err[err_count] = 'You must select a sport';
				err_count++;
			}
			else {
				values.bs = box_sport;
			}
			
			values.bdn = $('#ml_box_days_nr').val(); // box days number
			values.bmn = $('#ml_box_matches_nr').val(); // box matches number
			
			var box_league = getSelectedMlLeagues();
			if(box_league == null || box_league == '') {
				err[err_count] = 'You must select at least one league';
				err_count++;
			}
			else {
				values.bl = box_league.replace(/(^\.|\.$)/g, '');
			}
			
			if(box_sport != null && box_sport != '' && box_sport != 0) {
				var box_market = $('#ml_markets_' + box_sport).val();
				if(box_market > 0) {
					values.bm = box_market;
				}
				else {
					var ec = err_count - 1;
					err[err_count] = 'You must select a market';
					err_count++;
				}
			}
			
			
			var box_style = $('#ml_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
		}
		
		else if(box_type == 'dr') {
			var box_style = $('#dr_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
		}
		
		else if(box_type == 'tb') {
			var box_sport = $('#tb_box_sport').val();
			if(box_sport == null || box_sport == 0) {
				err[err_count] = 'You must select a sport';
				err_count++;
			}
			else {
				values.bs = box_sport;
			}
			
			var box_team_text = $('#tb_team_autocomplete').val();
			var box_team = $('#tb_box_team').val();
			
			if(box_team_text == '') {
				$('#tb_box_team').val('');
				var box_team = 0;
				err[err_count] = 'You must select a team';
				err_count++;
			}
			else if(typeof compareArr['tb'] == 'undefined' || typeof compareArr['tb'][box_team_text] == 'undefined' || box_team == null || box_team == 0) {
				$('#tb_box_team').val('');
				var box_team = 0;
				err[err_count] = "The specified team is not available! \nPlease select one from the suggested list!";
				err_count++;
			}
			else {
				var box_team = $('#tb_box_team').val();
				values.bteam = box_team;
			}
			
			var tb_opt = 0;
			if($('#tb_show_matches').attr("checked") === true) {
				values.showm = 1;
			}
			else {
				values.showm = 0;
				tb_opt++;
			}
			
			if($('#tb_show_tournaments').attr("checked") === true) {
				values.showt = 1;
			}
			else {
				values.showt = 0;
				tb_opt++;
			}
			
			if(tb_opt == 2) { // none of the options was selected
				err[err_count] = 'You must select at least one type of events to show';
				err_count++;
			}
			
			
			var box_style = $('#tb_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
		}
		
		else if(box_type == 'tm') {
			var box_sport = $('#tm_box_sport').val();
			if(box_sport == null || box_sport == 0) {
				err[err_count] = 'You must select a sport';
				err_count++;
			}
			else {
				values.bs = box_sport;
			}
			
			var box_team_text = $('#tm_team_autocomplete').val();
			var box_team = $('#tm_box_team').val();
			
			if(box_team_text == '') {
				$('#tm_box_team').val('');
				var box_team = 0;
				err[err_count] = 'You must select a team';
				err_count++;
			}
			else if(typeof compareArr['tm'] == 'undefined' || typeof compareArr['tm'][box_team_text] == 'undefined' || box_team == null || box_team == 0) {
				$('#tm_box_team').val('');
				var box_team = 0;
				err[err_count] = "The specified team is not available! \nPlease select one from the suggested list!";
				err_count++;
			}
			else {
				var box_team = $('#tm_box_team').val();
				values.bteam = box_team;
			}

			if(box_market_str == null || box_market_str == '' || box_market_str == '.') {
				var ec = err_count - 1;
				err[err_count] = 'You must select at least one market';
				err_count++;
			}
			else {
				values.bm = box_market_str.replace(/(^\.|\.$)/g, '');
				//alert(values.bm);
			}
			
			var box_outcomes_nr = $('#tm_box_outcomes_nr').val();
			if(box_outcomes_nr == null || box_outcomes_nr == 0) {
				err[err_count] = 'You must select a number of outcomes to show';
				err_count++;
			}
			else {
				values.bon = box_outcomes_nr;
			}
			
			var box_style = $('#tm_box_style').val();
			if(box_style == null || box_style == 0) {
				err[err_count] = 'You must select a style for the box';
				err_count++;
			}
			else {
				values.bst = box_style;
			}
		}
		
		var box_width = $('#' + box_type + '_box_width').val().replace(' ', '');
		
		if(values.bt == 'ml') {
			if(values.bm == 40 || values.bm == 981 || values.bm == 1454) {
				min_width = 620;
			}
			else {
				min_width = 450;
			}
		}
		else if(values.bt == 'tb') {
			min_width = 620;
		}
		else {
			min_width = 250;
		}
		
		if(box_width != '') {
			if(box_width >= min_width) {
				values.bw = box_width;
			}
			else {
				values.bw = min_width;
				$('#' + box_type + '_box_width').val(min_width);
				alert("The specified width is smaller than the minimum allowed for the current box type and parameters. \n It has been automatically adjusted to the minimum allowed width: " + min_width + "px !");
			}
		}
		else {
			values.bw = '';
		}
		
	}
	
	if(err.length > 0) {
		var errors = '';
		$.each(err, function(i, n) {
			errors += '- ' + n + "\n";
		});
		alert(errors);
		return false;
	}
	else {
		values.bi = $('#box_info').val();
		
		var values_str = '';
		var x = 0;
		$.each(values, function(i, n) {
			if(x > 0) {
				values_str += '&';
			}
			values_str += 'v[' + i + ']' + '=' + n;
			x++;
		});

		return values_str;
	}

}



function initSelectBoxType() {
	$('.ml_markets_sports').change(function() {
		var selected_market = $(':selected', this).val();
		if(selected_market == 40 || selected_market == 981 || selected_market == 1454) {
			min_width = 620;
		}
		else {
			min_width = 450;
		}
		$('#ml_min_width_span').text(min_width);
	});
	
	$('ul.select_box_type li.type_available').click(function() {
		var id = $(this).attr('id').replace('_selector', '');
		$('div.box_form_container').hide();
		$('div.' + id + '_container').fadeIn('fast');
		$('ul.select_box_type li.active').removeClass('active');
		$(this).addClass('active');
		$('#box_type').attr('value', id);
		if(id == 'ml' || id == 'tb') {
			min_width = 620;
		}
		else {
			min_width = 250;
		}
		$('#' + id + '_min_width_span').text(min_width);
	});
	$('ul.select_box_type li.type_not_available').click(function() {
		alert('This type of box is not available for the moment');
	});
}

function initSportSelect() {
	$('#st_box_sport').change(function(){
		var sport_name = $(this).val();
		ajaxGetCategoriesDD('#st_box_category', sport_name, 'st', 2);
	});
	$('#sm_box_sport').change(function(){
		var sport_name = $(this).val();
		ajaxGetCategoriesDD('#sm_box_category', sport_name, 'sm', 1);
	});
	$('#ml_box_sport').change(function(){
		var sport_name = $(this).val();
		mlSwitchMarketsActive(sport_name);
		resetMlLeagues();
		ajaxGetCategoriesDD('#ml_box_category', sport_name, 'ml', 1);
		if(ml_step_3 == 0) {
			$('div.ml_step_3').fadeIn('fast');
			ml_step_3 = 1;
		}
	});
	$('#tb_box_sport').change(function(){
		var sport_name = $(this).val();
		$('#tb_team_autocomplete').val('');
		$('#tb_box_team').val('');
		ajaxGetTeamsDD('#team_box_inputs_holder', sport_name, 'tb');
	});
	$('#tm_box_sport').change(function(){
		var sport_name = $(this).val();
		var market_category = 1;
		$('.tm_markets_input').val('');
		// populate markets selector
		ajaxGetMarketsDD('.tm_selector_container', sport_name, '', market_category, 'tm');
		
		// populate team autocomplete
		$('#tm_team_autocomplete').val('');
		$('#tm_box_team').val('');
		ajaxGetTeamsDD('#team_match_inputs_holder', sport_name, 'tm');
	});
	
}

function initCategorySelect(box_type) {
	if(box_type == 'st') {
		var sport_name = $('#st_box_sport').val();
		var category_name = $('#st_box_category').val();
		ajaxGetLeaguesDD('#st_box_league', sport_name, category_name, 'st', 2);
	}
	else if(box_type == 'sm') {
		var sport_name = $('#sm_box_sport').val();
		var category_name = $('#sm_box_category').val();
		ajaxGetLeaguesDD('#sm_box_league', sport_name, category_name, 'sm', 1);
	}
	else if(box_type == 'ml') {
		var sport_name = $('#ml_box_sport').val();
		var category_name = $('#ml_box_category').val();
		ajaxGetLeaguesDD('.l_selector_container_right .l_selector_container', sport_name, category_name, 'ml', 1);
		if(ml_step_4 == 0) {
			$('div.ml_step_4').fadeIn('fast');
			ml_step_4 = 1;
		}
	}
}

function initTeamSelect(box_type) {
	if(box_type == 'tb') {
		$('.tb_step_4').fadeIn('fast');
	}
}

function initLeagueSelect(box_type) {
	if(box_type == 'st') {
		if(st_step_3 == 0) {
			$('div.st_step_3').fadeIn('fast');
			st_step_3 = 1;
		}
		var sport_name = $('#st_box_sport').val();
		var league_id = $('#st_box_league').val();
		ajaxGetEventsDD('#st_box_event', sport_name, league_id, 2, 'st');
	}
	else if(box_type == 'sm') {
		if(sm_step_3 == 0) {
			$('div.sm_step_3').fadeIn('fast');
			sm_step_3 = 1;
		}
		var sport_name = $('#sm_box_sport').val();
		var league_id = $('#sm_box_league').val();
		ajaxGetEventsDD('#sm_box_event', sport_name, league_id, 1, 'sm');
	}
	else if(box_type == 'ml') {

	}
}

function initEventSelect(box_type) {
	if(box_type == 'st') {
		var sport_name = $('#st_box_sport').val();
		var event_id = $('#st_box_event').val();
		var market_category = 2;
		ajaxGetMarketsDD('#st_box_market', sport_name, event_id, market_category, box_type);
	}
	else if(box_type == 'sm') {
		var sport_name = $('#sm_box_sport').val();
		var event_id = $('#sm_box_event').val();
		var market_category = 1;
		ajaxGetMarketsDD('.m_selector_container', sport_name, event_id, market_category, box_type);
	}
	else if(box_type == 'ml') {
		var sport_name = $('#ml_box_sport').val();
		var event_id = $('#ml_box_event').val();
		var market_category = 1;
		ajaxGetMarketsDD('.ml_selector_container', sport_name, event_id, market_category, box_type);
	}
}

function initMarketSelect(market_category) {
	if(market_category == 2) {
		if(st_step_4 == 0) {
			$('div.st_step_4').fadeIn('fast');
			st_step_4 = 1;
		}
	}
	else {
		if(sm_step_4 == 0) {
			$('div.sm_step_4').fadeIn('fast');
			sm_step_4 = 1;
		}
	}
}

function buildBoxTypeStr(box_type) {
	if(box_type == 'sm' || box_type == 'st' || box_type == 'ml' || box_type == 'tb'  || box_type == 'tm') {
		bt_str = "&bt=" + box_type;
	}
	else {
		bt_str = "";
	}
	return bt_str;
}

function ajaxGetCategoriesDD(dd_selector, sport_name, box_type, market_category) {
	bt_str = buildBoxTypeStr(box_type);
	$.ajax({
	 type: "POST",
	 url: base_url + "odds-boxes/ajax/",
	 data: "action=get_sport_categories&sport_name=" + sport_name + "&market_category=" + market_category + bt_str,
	 async: false,
	 success: function(html){
		 $(dd_selector).replaceWith(html);
		 
	 }
 });
	resetLeagueSelect(box_type);
}

function ajaxGetTeamsDD(dd_selector, sport_name, box_type) {
	bt_str = buildBoxTypeStr(box_type);
	$.ajax({
	 type: "POST",
	 url: base_url + "odds-boxes/ajax/",
	 data: "action=get_sport_teams&sport_name=" + sport_name + bt_str,
	 async: false,
	 success: function(html){
		 $(dd_selector).html(html);
		 
	 }
 });
	resetLeagueSelect(box_type);
}

function mlSwitchMarketsActive(sport_name) {
	if(sport_name != null) {
		$('.ml_markets_dd_holder select.active').removeClass('active');
		$('.ml_markets_dd_holder select#ml_markets_' + sport_name).addClass('active');
	}
}

function ajaxGetLeaguesDD(dd_selector, sport_name, category_name, box_type, market_category) {
	bt_str = buildBoxTypeStr(box_type);
	if(box_type == 'ml') {
		selected_leagues = "&selected_leagues=" + box_league_str;
	}
	else {
		selected_leagues = "";
	}
	$.ajax({
	 type: "POST",
	 url: base_url + "odds-boxes/ajax/",
	 data: "action=get_sport_categories_leagues&sport_name=" + sport_name + "&category_name=" + category_name + "&market_category=" + market_category + bt_str + selected_leagues,
	 async: false,
	 success: function(html){
		 $(dd_selector).replaceWith(html);
	 }
 });
	resetEventSelect(box_type);
}

function ajaxGetEventsDD(dd_selector, sport_name, league_id, market_category, box_type) {
	bt_str = buildBoxTypeStr(box_type);
	$.ajax({
	 type: "POST",
	 url: base_url + "odds-boxes/ajax/",
	 data: "action=get_league_events&sport_name=" + sport_name + "&league_id=" + league_id + "&market_category=" + market_category + bt_str,
	 async: false,
	 success: function(html){
		 $(dd_selector).replaceWith(html);
	 }
 });
	resetMarketSelect(box_type);
}

function ajaxGetMarketsDD(dd_selector, sport_name, event_id, market_category, box_type) {
	if(market_category == 1 || box_type == 'sm') {
		resetMarketSelect('sm');
	}
	
	bt_str = buildBoxTypeStr(box_type);

	$.ajax({
	 type: "POST",
	 url: base_url + "odds-boxes/ajax/",
	 data: "action=get_event_markets&sport_name=" + sport_name + "&event_id=" + event_id + "&market_category=" + market_category + bt_str,
	 async: false,
	 success: function(html){
		 $(dd_selector).replaceWith(html);
	 }
 });
}

function resetLeagueSelect(box_type) {
	$('#' + box_type + '_box_league').replaceWith(boxes[box_type]["box_league"]);
	resetEventSelect(box_type);
}

function resetEventSelect(box_type) {
	$('#' + box_type + '_box_event').replaceWith(boxes[box_type]["box_event"]);
	resetMarketSelect(box_type);
}

function resetMarketSelect(box_type) {
	$('#' + box_type + '_box_market').replaceWith(boxes[box_type]["box_market"]);
	if(box_type == 'sm') {
		$('.m_selector_container').html('&nbsp;');
		$('.sm_markets_input').attr('value', '');
		box_market_str = '';
	}
}

function resetMlLeagues() {
	$('.leagues_table_container table.l_select_left_table tbody tr, .leagues_table_container table.l_select_right_table tbody tr').remove();
}

function getSelectedMlLeagues() {
	var position = 1;
	var box_league_str = '';
		
	$('.leagues_table_container table.l_select_left_table tbody tr').each(function () {
		var h = $('td:last', $(this));
		var l_id = h.attr('class').replace('rem_league rem_l_', '');
		if(position > 1) {
			box_league_str += l_id + '.';
		}
		else {
			box_league_str = '.' + l_id + '.';
		}
		position += 1;
	});	
	return box_league_str;
}


function initTeamAutocomplete(bt) {
		$("#" + bt + "_team_autocomplete").autocompleteArray(
		acpl_teams[bt], 
		{
			autoFill: true, 
			delay: 100, 
			selectFirst: true,
			subArray: bt,
			receiverId: '#' + bt + '_box_team',
			formatItem: function(row, i, num) {
				return row;
			}
		});
	}