function _(msgid){
	if(Locale == undefined || Locale[msgid] == undefined){
		return msgid;
	}else{
		return Locale[msgid];
	}
}

var selectSort = function(select){
	var my_options = select.children("option");
	my_options.sort(function(a,b) {
	    if (a.text > b.text) return 1;
	    else if (a.text < b.text) return -1;
	    else return 0
	})
	select.empty().append(my_options);	
}

var multiselect = function(selector){
	var selected = $(selector);
	selected.attr('multiple', 'multiple'); // ensure multiple selection
	selected.wrap('<div class="multiselect" />');
	var container = selected.parent();
	container.hide();
	var available = selected.clone().removeAttr('name').removeAttr('id');
	selected.addClass('selected');
	selected.children(':not(:selected)').remove();
	available.addClass('available');
	available.children(':selected').remove();
	var controls = $('<div class="controls" />');
	var control_all = $('<a class="all" href="#" />').text(_('all')).click(multiselectAll);
	controls.append(control_all).append('<br />');
	var control_add = $('<a class="add" href="#" />').text('»').click(multiselectAdd);
	controls.append(control_add).append('<br />');
	var control_rm  = $('<a class="remove" href="#" />').text('«').click(multiselectRemove);
	controls.append(control_rm);
	container.prepend(controls);
	container.prepend(available);
	container.parents('form').submit(multiselectSubmit);
	container.show();
}

var multiselectAdd = function(){
	var selected = $(this).parent().siblings('.selected');
	var available = $(this).parent().siblings('.available');
	available.children(':selected').appendTo(selected);
	selectSort(selected);
	return false;
}

var multiselectRemove = function(){
	  var selected = $(this).parent().siblings('.selected');
	  var available = $(this).parent().siblings('.available');
	  selected.children(':selected').appendTo(available);
	  selectSort(available);
	  return false;
}

var multiselectAll = function(){
	$(this).parent().siblings('select').children(':not(:selected)').attr('selected', 'selected');
	return false;
}

var multiselectSubmit = function(){
	$('.multiselect .selected option').attr('selected', 'selected');
}


function displayFlash(msg, title){
	if(title == undefined || title == null){
		title = 'Note';
	}
	var flash = $('#flashnotice');
	if(flash.length == 0){
		flash = $('<div>').attr('id', 'flashnotice').hide().prependTo('#content');
	}else{
		flash.hide();
		flash.empty();
	}
	// set title
	$('<h2>').text(title).appendTo(flash);
	if(typeof msg == 'string'){
		$('<p>').text(msg).appendTo(flash);
	}else if($.isArray(msg) && msg.length == 1){
		$('<p>').text(msg.shift()).appendTo(flash);
	}else if($.isArray(msg)){
		var ul = $('<ul>');
		while(msg.length > 0){
	   	 	var li = $('<li>');
	   	 	li.text(msg.shift());
	  	 	ul.append(li);
	   	}
		flash.append(ul);
	}
	
	flashNoticeAnimation();
}

function flashNoticeAnimation(){
	var flash = $('#flashnotice');
	if(flash.length == 1){
		flash.hide();
		flash.fadeIn("slow");
		window.setTimeout(function(){
			flash.fadeOut("slow");
		}, 13000);
	}
}

function isValid(selector, minLength){
	if(minLength == undefined){
		minLength = 1;
	}
	if($(selector).val().length < minLength){
		$(selector).addClass('invalid');
		return false;
	}else{
		return true;
	}
}

function countryChanged(){
	// TODO improve this
	// USA
	var usstate = $('#iusstate');
	if($('#icountry').val() == 'US'){
		usstate.parent().slideDown();
	}else if(usstate.css('visibility') != 'hidden'){
		usstate.parent().slideUp();
	}
	// China
	var cnstate = $('#icnstate');
	if($('#icountry').val() == 'CN'){
		cnstate.parent().slideDown();
	}else if(cnstate.css('visibility') != 'hidden'){
		cnstate.parent().slideUp();
	}
	return false;
}

function distributorChoiceChanged(){
	var choice = $('#idistributorchoice');
	var distributor = $('#idistributor');
	
	if(choice.val() == 'other'){
		distributor.parent().slideDown();
	}else if(distributor.css('visibility') != 'hidden'){
		distributor.parent().slideUp();
	}
}

function validEmail(email){
	return !(email.search(/^.+@[^\.].*\.[a-z]{2,}$/) == -1);
}

function validPhone(phone){
	return !(phone.search(/^[0-9\s\(\)\+\-]+$/) == -1);
}

function validateAccountData(){
	$('.invalid').removeClass('invalid');
	var err_msg = new Array();	
	if(!isValid('#ifirstname')){
		err_msg.push(_('Please enter your first name.'));
	}
	if(!isValid('#ilastname')){
		err_msg.push(_('Please enter your last name.'));
	}
	if(!isValid('#iphone')){
		err_msg.push(_('Please enter your phone number.'));
	}else if(!validPhone($('#iphone').val())){
		err_msg.push(_('The phone number does not seem to be valid.'));
	}
    if(!isValid('#iemail')){
    	err_msg.push('Please enter your email address.');
    }else if(!validEmail($('#iemail').val())){
    	err_msg.push(_('The email address does not seem to be valid.'));
    }
	if(!isValid('#iname')){
		err_msg.push(_('Please enter the name of your organization.'));
	}
    if(!isValid('#istreet')){
	 	err_msg.push(_('Please enter your street/postbox.'));
	}
	if(!isValid('#icity')){
		err_msg.push(_('Please enter your city.'));
	}
    if($('#icountry').val() == '0'){
    	$('#icountry').addClass('invalid');
      	err_msg.push(_('Please select your country.'));
    }else if($('#icountry').val() == 'US' && $('#iusstate').val() == '0'){
    	$('#iusstate').addClass('invalid');
    	err_msg.push(_('Please select your state.'));
    }else if($('#icountry').val() == 'CN' && $('#icnstate').val() == '0'){
    	$('#icnstate').addClass('invalid');
    	err_msg.push(_('Please select your province.'));
    }
    if($('#idistributorchoice').length == 1){
    	if($('#idistributorchoice').val() == '0'){
    		$('#idistributorchoice').addClass('invalid');
    		err_msg.push(_('Please tell us where you buy our products.'));
    	}else if($('#idistributorchoice').val() == 'other'){
    		if(!isValid('#idistributor')){
    			err_msg.push(_('Please enter the name of your distributor.'));
    		}
    	}
    }
    return err_msg;
}

function submitRegister(){
  var submit = $(this).find('input[type=submit]');
  submit.attr('disabled', 'disabled');
  var err_msg = new Array();	
  err_msg = err_msg.concat(validateAccountData());
  
  if($('#itac').attr('checked') == false){
  	err_msg.push(_('Please read and accept our Terms and Conditions.'));
  }
  
  if($('#iprivpol').attr('checked') == false){
   	err_msg.push(_('Please read and accept our Privacy Policy.'));
  }
  
  if(err_msg.length == 0){
  	return true;
  }else{
	submit.removeAttr('disabled');
	document.location = '#';
  	displayFlash(err_msg);
  	return false;
  }
}

function submitAccount(){
	var submit = $(this).find('input[type=submit]');
	submit.attr('disabled', 'disabled');
    var err_msg = validateAccountData();
    
    if(err_msg.length == 0){
    	return true;
    }else{
    	submit.removeAttr('disabled');
    	displayFlash(err_msg);
    	document.location = '#';
    	return false;
    }
}

function submitLostPassword(){
	$('.invalid').removeClass('invalid');
	var email = $('#lost_password_form #iemail');
	if(email.val() == ''){
		displayFlash(_('You have to enter your e-mail address in order to receive a new password.'));
		email.addClass('invalid');
		return false;
	}else if(!validEmail(email.val())){
		displayFlash(_('The email address does not seem to be valid.'));
		email.addClass('invalid');
		return false;
	}
	return true;
}

function submitChangePassword(){
	var submit = $(this).find('input[type=submit]');
	submit.attr('disabled', 'disabled');
	var err_msg = new Array();
	
	if(!isValid('#ipassword1') || !isValid('#ipassword2')){
		err_msg.push(_('Please enter your new password twice.'));
	}else{
		if(!isValid('#ipassword1', 6)){
			err_msg.push(_('Your password must be at least 6 characters long.'));
		}
		if($('#ipassword1').val() != $('#ipassword2').val()){
			err_msg.push(_('The two fields must contain the same password.'));
		}
	}
	
	if(err_msg.length == 0){
		return true;
	}else{
		submit.removeAttr('disabled');
		displayFlash(err_msg);
		return false;
	}
}

function submitRegisterProduct(){
	var submit = $(this).find('input[type=submit]');
	submit.attr('disabled', 'disabled');
	var err_msg = new Array();
	
	if(($('select#product').length == 1) && ($('select#product').val() == 0)){
		err_msg.push(_('Please select your product.'));
	}
	if(($('select#distributor').length == 1) && ($('select#distributor').val() == 0)){
		err_msg.push(_('Please select your distributor.'));
	}
	if(err_msg.length == 0){
		return true;
	}else{
		submit.removeAttr('disabled');
		displayFlash(err_msg);
		return false;
	}
}

function submitRegisterCode(){
	return ($.trim($('#code').val()).length != 0);
}

function submitCountry(){
	var error = false;
	if($('#country_id').length = 1){
		error = error && $.trim($('#country_id').val()).length == 2;
	}
	error = error && $.trim($('#country').val()).length != 0;
	return error;
}

function clickFAQLink(){
    $(this).parent().siblings().slideToggle();
    return false;
}

function clickStatisticsLink(){
	var hl = $('#content h2, #content h3');
	hl.next('div').hide();
	hl.css('cursor', 'pointer');
	hl.click(function(){ $(this).next('div').slideToggle(); });
	$('div.startopen').show();
	return false;
}

function submitDeleteProduct(){
	return confirm(_('Do you really want to irrevocably delete this product?'));
}

function submitDeleteWeb2LeadForm(){
	return confirm(_('Do you really want to irrevocably delete this Web2Lead form?'));
}

function submitDeleteReward(){
	return confirm(_('Do you really want to irrevocably delete this reward?'));
}

function submitDeleteCountry(){
	return confirm(_('Do you really want to irrevocably delete this country?'));
}

function submitDeleteDistributor(){
	return confirm(_('Do you really want to irrevocably delete this distributor?'));
}

function submitDeleteUser(){
	return confirm(_('Do you really want to irrevocably delete this user?'));
}

function submitDeleteDownload(){
	return confirm(_('Do you really want to irrevocably delete this download?'));
}

function submitDeleteSalesRep(){
	return confirm(_('Do you really want to irrevocably delete this sales representative?'));
}

function submitCustomerSearch(data){
	var form = $('form#customer_search');
	form.next('#loader').replaceWith(data);
	form.find('input[type=submit]').removeAttr('disabled');
}

function submitCustomerCredit(){
	  $('.invalid').removeClass('invalid');
	  var pv = $(this).find('#pointvalue');
	  var confirmed_value = false;
	  
	  if(pv.val() < 0){
	    confirmed_value = confirm(_("Do you really want to deduct AMOUNT %s from this customer's account?").replace('AMOUNT', pv.val()));
	  }else if(pv.val() > 0){
		confirmed_value = confirm(_("Do you really want to credit AMOUNT %s to this customer's account?").replace('AMOUNT', pv.val()));
	  }
	  if(pv.val() == 0 || pv.val() == '' || !confirmed_value){
		pv.addClass('invalid');
	  }
	  var reason_select = $(this).find('#reason_default');
	  var reason = $(this).find('#reason');
	  if(reason_select.val() == '' && reason.val() == ''){
	    reason_select.addClass('invalid');
	    reason.addClass('invalid');
	  }
	  return $('.invalid').length == 0;
}

function templateIndexChanged(){
	var idx = $('.templateeditor #index').val();
	var editor = $('.templateeditor #template');
	var submit = $('.templateeditor input[type=submit]')
	editor.attr('disabled', 'disabled');
	editor.text('');
	submit.attr('disabled', 'disabled');
	if(idx != ''){
		$.get('/master/templates/', {action : 'get', index : idx}, function(data){
			editor.text(data);
			editor.removeAttr('disabled');
			submit.removeAttr('disabled');
		}, 'text');
	}
}
