// this is number *ordering* not the country popup
jQuery(document).ready(function(){

	// hide number selection
	jQuery('.select-numbers').hide();

	// pressing add country or add region will trigger the add form to show
	jQuery('.add_country a, .add_region a').click(function(){
		jQuery('.select-numbers').slideDown(200);
		jQuery('.add_country').animate({opacity:0});
	});

	// save or cancel - hide the form
	jQuery('.cancel a, .save a').click(function(){
		jQuery('.select-numbers').slideUp(300);
		jQuery('.numbers-bottomblock').prepend(
			jQuery('.add_country').detach()
		);
		jQuery('.add_country').animate({opacity:1});
	});

	// focus/blur of the quanta box
	jQuery('.select-numbers .quantity').focus(function(){

		// set my label to active (going to overlay so changing colours)
		jQuery(this).prev().addClass('active');
		priceMatrix(jQuery(this).position());
	});
	jQuery('.select-numbers .quantity').blur(function(){
		jQuery(this).prev().removeClass('active');
		priceMatrix();
	});

	// edit of the quanta box
	jQuery('.select-numbers .quantity').keyup(function(){

		// if number < 1 or > 999, reset to 1
		var quanta = parseInt(jQuery('.select-numbers .quantity').val());
//		if(isNaN(quanta) || quanta < 1 || quanta > 999){
		if(quanta > 999){
			if(quanta < 1 || isNaN(quanta))  quanta=1;
			if(quanta > 999) quanta=999;
			jQuery('.select-numbers .quantity').val(quanta);
		}

		// search for the row
		jQuery('.number_amount_popup ul li').removeClass('active');
		jQuery('.number_amount_popup ul li').each(function(){

			// get range and price from the table
			var range_text = jQuery('span',jQuery(this)).eq(0).text();
			var price_text = jQuery('span',jQuery(this)).eq(1).text();

			// extract the higher and lower bounds from "1 &ndash; 10", "1000+" etc...
			var re  = /(\d*)\D*(\d*)/
			var range_values = re.exec(range_text);
			var lower_end = parseInt(range_values[1]);
			var upper_end = parseInt(range_values[2]);

			// extract the price
// from DB

			// check against range
			if(quanta >= lower_end){

				// found lower bound, check upper, or don't check if we hit the top
				if(! upper_end){ // no more ranges
					jQuery(this).addClass('active');
					return false;
				}
				else if(quanta <= upper_end){ // within range
					jQuery(this).addClass('active');
					return false;
				}
			}			
		});
	});

	function priceMatrix(position){
		if(!position){
			jQuery('.number_amount_popup').fadeOut(350);
		}
		else{
			jQuery('.number_amount_popup').css({
				position:'absolute',
				top:position.top,
				left:position.left,
				zIndex:50
			});
			jQuery('.number_amount_popup').fadeIn(200);
		}
	}

	// attach to delete events
	function setupEvents(ofCountry){

		if(!ofCountry) ofCountry=document;

		// pressing add country or add region will trigger the add form to show
		jQuery('.add_country a, .add_region a', ofCountry).click(function(){
			jQuery('.select-numbers').slideDown(200);
			jQuery('.add_country').animate({opacity:0});
		});

		jQuery('.country-close a, .region-close a').click(function(){

			// get the row type
			row = jQuery(this).parent().parent();

			// if it's a country, remove all regions first
			if(jQuery(row).hasClass('country')){
				// if the next row is a region, remove it
				if(jQuery(row).next().hasClass('region')){
					jQuery(row).next().slideUp(200, function(){jQuery(this).remove();});
				}
				// if, having removed the region, next row is an "add another region" - remove it
				if(jQuery(row).next().next().hasClass('add_region')){
					jQuery(row).next().next().slideUp(200, function(){jQuery(this).remove();});
				}
			}

			// if it's a region
			else{
				// some logic
				firstInCountry=jQuery(row).prev().hasClass('country');
				lastInCountry=jQuery(row).next().hasClass('add_region');
				onlyRegion=firstInCountry && lastInCountry;

				// if only region, click the parent instead
				if(onlyRegion){
					jQuery('.country-close a', jQuery(row).prev()).click();
				}

				// just removing a single region
				else{
				}
			}

			// either way, definitely remove this one
			jQuery(row).fadeOut(400, function(){
				jQuery(this).remove();
			});

		});
	}

	// save functionality (create a new LI)
	jQuery('.save').click(function(){

		// check if the country exists in list - if so, find it, if not, create it
		if(false){
			// find country and set to thisCountry
		}
		else{
			countryLi='<li class="country country_argentina">'+
			'<div class="country-countries">'+
				'<span><a><img src="/template/images/flag-1.gif" width="20" height="14" alt=""></a></span>'+
				'<p>Argentina</p>'+
			'</div>'+
			'<div class="country-numb-in">'+
				'<p>1</p>'+
			'</div>'+
			'<div class="country-cost">'+
				'<p>&pound;5.00</p>'+
			'</div>'+
			'<div class="country-rental">'+
				'<p>&pound;5.00</p>'+
			'</div>'+
			'<div class="country-total">'+
				'<p>&pound;5.00</p>'+
			'</div>'+
			'<div class="country-close"><a><img src="/template/images/gray-cross.png" width="8" height="8" alt=""></a></div>'+
			'<div class="clearflt"></div>'+
			'</li>'+
			'<li class="add_region"><a>Add another Region</a></li>';

			// add a country if required
			thisCountry = jQuery('.numbers-topblock').append(countryLi);
		}

		regionLi='<li class="region">'+
			'<div class="region-countries">'+
			'<span><a href=""><img src="/template/images/dot-1.gif" width="20" height="14" alt=""></a></span>'+
			'<p>Landline &mdash; Sau Paulo</p>'+
			'</div>'+
			'<div class="region-numb-in">'+
			'<p>1</p>'+
			'</div>'+
			'<div class="region-cost"><p>&pound;5.00</p></div>'+
			'<div class="region-rental">'+
			'<p>&pound;5.00</p>'+
			'</div>'+
			'<div class="region-total">'+
			'<p>&pound;5.00</p>'+
			'</div>'+
			'<div class="region-close"><a><img src="/template/images/gray-cross.png" width="8" height="8" alt=""></a></div>'+
			'<div class="clearflt"></div>'+
		'</li>';

		// add the new region
		thisRegion = jQuery('.add_region',thisCountry).before(regionLi);

		setupEvents(thisCountry);
	});

	setupEvents();
});

// add events for country selector popup
jQuery(document).ready(function(){
	jQuery(document.body).append(
		'<div class="country_selecta" style="display: none; ">'+
			'<div class="inner-cont-bot-left-top"></div>'+
			'<div class="inner-cont-bot-left-top2"><h2>Choose a country</h2></div>'+
			'<div class="inner-cont-bot-left-in">'+
				'<div class="country">'+
					'<div class="clear"></div>'+
				'</div>'+
			'</div>'+
			'<div class="inner-cont-bot-left-bot"></div>'+
		'</div>'
	);

	// the dropdown for new numbers
	jQuery('.country_selecta').hide(); // ensure hidden
	jQuery('.signup-country a').click(function(){
		showCountryChooser();
	});

	// see if we want to auto-open
	var hashTag=document.URL.split('#')[1];
	if((typeof hashTag !== 'undefined') && 'choosecountry'==hashTag){
		showCountryChooser();
	}
});

/**
  * @desc   Handles displaying a single chosen country when chosen from country selector
  * @author Leo Brown
  *
  *
  */
function chooseCountry(country){

	jQuery('.country_selecta').fadeOut().slideUp();

	// we've already pressed this once, so change the text and class to show so
	jQuery('.signup-country a')
		.text('Change Country')
		.addClass('change_country');

	jQuery('#selected_countryinfo').remove();

	// flag
	matched = jQuery(".country_selecta a:contains('"+ country +"')");

	jQuery('.signup-country a').after(
		'<div id="selected_countryinfo">'+
			'<span class="countrylabel">' + 
				'Country'+
			'</span>'+
			'<span class="selected_country">' + 
				jQuery(matched).html()+
			'</span>'+
			'<span class="countrylabel">' + 
				'Region'+
			'</span>'+
			'<span class="selected_country">' + 
				'<select id="number_regions" name="number_region"></select>' +
			'</span>'+
		'</div>'
	);

	// add the regions to the select
	populateRegions(country);
}

function populateRegions(country){

	// get the list of countries
	url='http://vox.netfuse.org/number_regions/regions/'+country;
	jQuery.ajax({
		url: url,
		success: function(data){

			// process country data
			regions = jQuery.parseJSON(data);

			// create a list of options to add
			regionHTML='';
			for(r in regions){
				thisRegion=regions[r];
				regionHTML+='<option value="' +
					thisRegion.Country.number +
					thisRegion.NumberRegion.number +
					'">'+ 
						thisRegion.NumberRegion.name + 
						' (+' + thisRegion.Country.number + thisRegion.NumberRegion.number + ')' +
					'</option>';
			}

			jQuery('#number_regions').html(regionHTML);

			// if using select box
			jQuery("#number_regions").selectBox();
//	                jQuery('#number_regions').selectBox().change( function() { alert( jQuery(this).val() ); } );
		}
	});

}


/**
  * @desc   Show the country selector
  * @todo   Add parameter to pass the function to be called once a country is chosen
  * @author Leo Brown
  *
  *
  */
var countriesLoaded = false;
function showCountryChooser(){

	// remove any already chosen country
	jQuery('#selected_countryinfo select').selectBox('destroy');  // TEST For this functionality first
	jQuery('#selected_countryinfo').remove();

	// show the selector, and put it where the add button was
	jQuery('.country_selecta').css({
		position: 'absolute',
		top: jQuery('.signup-country').position().top -12,
		left: jQuery('.signup-country').position().left -10
	})
	.fadeIn(200);

	// get the list of countries
	url='http://vox.netfuse.org/number_regions/countries';
	if(!countriesLoaded) jQuery.ajax({
		url: url,
		success: function(data){

			// process country data
			countries = jQuery.parseJSON(data);
			countriesLoaded = true;

			// get total
			columns = Math.round(countries.length/3)+1;
			i=0;
			countrylist  = '<div class="country_list">';
			countrylist += '<ul>';
			for(c in countries){

				// do we want to start a UL?				
				startcolumn = 0 == (i % columns);
				//console.log(i + ' is index ' + columns + ' is column count and so starting col? ' + startcolumn);

				// useful info
				country = countries[c].Country;
				flag='http://netfuse.org/img/flagicons/gif/' + country.iso.toLowerCase() + '.gif';

				if(startcolumn){
					countrylist += '</ul><ul>';
				}

				countrylist += '<li style="display:none">';
				countrylist += '<a>';
				countrylist += '<span class="flag">';
				countrylist += '<img width="20" height="14" alt="" src="'+flag+'">';
				countrylist += '</span>';
				countrylist += '<span class="country-text">';
				countrylist += country.name;
				countrylist += '</span>';
				countrylist += '<span class="clearflt"></span>';
				countrylist += '</a>';
				countrylist += '</li>';
				i++;
			}
			countrylist+='</ul>';
			jQuery('.country_selecta .country').append(countrylist);

			scrollto=jQuery('#signup_number_country_container').position().top - 100;

			jQuery('html, body').delay(300).animate(
				{scrollTop: scrollto},
				1100,
				'swing',
				function(){
					// enable them one by one
					i=0;
					for(c in countries){
						jQuery('.country_selecta ul li').eq(c).delay(i*20).fadeIn(85);
						i++;
					}
				}
			);

			// action of clicking on a country
			jQuery('.country_selecta ul li').click(function(){
				chooseCountry(jQuery(this).text());
			});

		}

	});
}

