/**  
 * Custom Javascript for specific fields.
 * 
 * Author: Eduardo A. Romero
 * email : eromero {at} agileweb.mx
 * 
 */

var country_input_id = '';
var state_input_id   = '';

var country_input_name = '';
var state_input_name = '';

var country_default  = 'US';

var states_url = '/javascript/states/';

function bind_specifics() {
	country_list();	
}


function enable_caledar_pickers(elements) {
	var defaults = {
			showOn: 'both',
			buttonImageOnly: true,
			buttonText: 'Select a date...',
			dateFormat: 'yy-mm-dd',
			buttonImage: '/img/bluetrip/icons/calendar.png'
	};
	 
	jQuery.each(elements, function(index, element) {
		$(element).datepicker(defaults);
	});
}

function country_list() {
    var countries =  {"AF":"AFGHANISTAN","AX":"\u00c5LAND ISLANDS","AL":"ALBANIA","DZ":"ALGERIA","AS":"AMERICAN SAMOA","AD":"ANDORRA","AO":"ANGOLA","AI":"ANGUILLA","AQ":"ANTARCTICA","AG":"ANTIGUA AND BARBUDA","AR":"ARGENTINA","AM":"ARMENIA","AW":"ARUBA","AU":"AUSTRALIA","AT":"AUSTRIA","AZ":"AZERBAIJAN","BS":"BAHAMAS","BH":"BAHRAIN","BD":"BANGLADESH","BB":"BARBADOS","BY":"BELARUS","BE":"BELGIUM","BZ":"BELIZE","BJ":"BENIN","BM":"BERMUDA","BT":"BHUTAN","BO":"BOLIVIA, PLURINATIONAL STATE OF","BA":"BOSNIA AND HERZEGOVINA","BW":"BOTSWANA","BV":"BOUVET ISLAND","BR":"BRAZIL","IO":"BRITISH INDIAN OCEAN TERRITORY","BN":"BRUNEI DARUSSALAM","BG":"BULGARIA","BF":"BURKINA FASO","BI":"BURUNDI","KH":"CAMBODIA","CM":"CAMEROON","CA":"CANADA","CV":"CAPE VERDE","KY":"CAYMAN ISLANDS","CF":"CENTRAL AFRICAN REPUBLIC","TD":"CHAD","CL":"CHILE","CN":"CHINA","CX":"CHRISTMAS ISLAND","CC":"COCOS (KEELING) ISLANDS","CO":"COLOMBIA","KM":"COMOROS","CG":"CONGO","CD":"CONGO, THE DEMOCRATIC REPUBLIC OF THE","CK":"COOK ISLANDS","CR":"COSTA RICA","CI":"C\u00d4TE D'IVOIRE","HR":"CROATIA","CU":"CUBA","CY":"CYPRUS","CZ":"CZECH REPUBLIC","DK":"DENMARK","DJ":"DJIBOUTI","DM":"DOMINICA","DO":"DOMINICAN REPUBLIC","EC":"ECUADOR","EG":"EGYPT","SV":"EL SALVADOR","GQ":"EQUATORIAL GUINEA","ER":"ERITREA","EE":"ESTONIA","ET":"ETHIOPIA","FK":"FALKLAND ISLANDS (MALVINAS)","FO":"FAROE ISLANDS","FJ":"FIJI","FI":"FINLAND","FR":"FRANCE","GF":"FRENCH GUIANA","PF":"FRENCH POLYNESIA","TF":"FRENCH SOUTHERN TERRITORIES","GA":"GABON","GM":"GAMBIA","GE":"GEORGIA","DE":"GERMANY","GH":"GHANA","GI":"GIBRALTAR","GR":"GREECE","GL":"GREENLAND","GD":"GRENADA","GP":"GUADELOUPE","GU":"GUAM","GT":"GUATEMALA","GG":"GUERNSEY","GN":"GUINEA","GW":"GUINEA-BISSAU","GY":"GUYANA","HT":"HAITI","HM":"HEARD ISLAND AND MCDONALD ISLANDS","VA":"HOLY SEE (VATICAN CITY STATE)","HN":"HONDURAS","HK":"HONG KONG","HU":"HUNGARY","IS":"ICELAND","IN":"INDIA","ID":"INDONESIA","IR":"IRAN, ISLAMIC REPUBLIC OF","IQ":"IRAQ","IE":"IRELAND","IM":"ISLE OF MAN","IL":"ISRAEL","IT":"ITALY","JM":"JAMAICA","JP":"JAPAN","JE":"JERSEY","JO":"JORDAN","KZ":"KAZAKHSTAN","KE":"KENYA","KI":"KIRIBATI","KP":"KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF","KR":"KOREA, REPUBLIC OF","KW":"KUWAIT","KG":"KYRGYZSTAN","LA":"LAO PEOPLE'S DEMOCRATIC REPUBLIC","LV":"LATVIA","LB":"LEBANON","LS":"LESOTHO","LR":"LIBERIA","LY":"LIBYAN ARAB JAMAHIRIYA","LI":"LIECHTENSTEIN","LT":"LITHUANIA","LU":"LUXEMBOURG","MO":"MACAO","MK":"MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF","MG":"MADAGASCAR","MW":"MALAWI","MY":"MALAYSIA","MV":"MALDIVES","ML":"MALI","MT":"MALTA","MH":"MARSHALL ISLANDS","MQ":"MARTINIQUE","MR":"MAURITANIA","MU":"MAURITIUS","YT":"MAYOTTE","MX":"MEXICO","FM":"MICRONESIA, FEDERATED STATES OF","MD":"MOLDOVA, REPUBLIC OF","MC":"MONACO","MN":"MONGOLIA","ME":"MONTENEGRO","MS":"MONTSERRAT","MA":"MOROCCO","MZ":"MOZAMBIQUE","MM":"MYANMAR","NA":"NAMIBIA","NR":"NAURU","NP":"NEPAL","NL":"NETHERLANDS","AN":"NETHERLANDS ANTILLES","NC":"NEW CALEDONIA","NZ":"NEW ZEALAND","NI":"NICARAGUA","NE":"NIGER","NG":"NIGERIA","NU":"NIUE","NF":"NORFOLK ISLAND","MP":"NORTHERN MARIANA ISLANDS","NO":"NORWAY","OM":"OMAN","PK":"PAKISTAN","PW":"PALAU","PS":"PALESTINIAN TERRITORY, OCCUPIED","PA":"PANAMA","PG":"PAPUA NEW GUINEA","PY":"PARAGUAY","PE":"PERU","PH":"PHILIPPINES","PN":"PITCAIRN","PL":"POLAND","PT":"PORTUGAL","PR":"PUERTO RICO","QA":"QATAR","RE":"R\u00c9UNION","RO":"ROMANIA","RU":"RUSSIAN FEDERATION","RW":"RWANDA","BL":"SAINT BARTH\u00c9LEMY","SH":"SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA","KN":"SAINT KITTS AND NEVIS","LC":"SAINT LUCIA","MF":"SAINT MARTIN","PM":"SAINT PIERRE AND MIQUELON","VC":"SAINT VINCENT AND THE GRENADINES","WS":"SAMOA","SM":"SAN MARINO","ST":"SAO TOME AND PRINCIPE","SA":"SAUDI ARABIA","SN":"SENEGAL","RS":"SERBIA","SC":"SEYCHELLES","SL":"SIERRA LEONE","SG":"SINGAPORE","SK":"SLOVAKIA","SI":"SLOVENIA","SB":"SOLOMON ISLANDS","SO":"SOMALIA","ZA":"SOUTH AFRICA","GS":"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS","ES":"SPAIN","LK":"SRI LANKA","SD":"SUDAN","SR":"SURINAME","SJ":"SVALBARD AND JAN MAYEN","SZ":"SWAZILAND","SE":"SWEDEN","CH":"SWITZERLAND","SY":"SYRIAN ARAB REPUBLIC","TW":"TAIWAN, PROVINCE OF CHINA","TJ":"TAJIKISTAN","TZ":"TANZANIA, UNITED REPUBLIC OF","TH":"THAILAND","TL":"TIMOR-LESTE","TG":"TOGO","TK":"TOKELAU","TO":"TONGA","TT":"TRINIDAD AND TOBAGO","TN":"TUNISIA","TR":"TURKEY","TM":"TURKMENISTAN","TC":"TURKS AND CAICOS ISLANDS","TV":"TUVALU","UG":"UGANDA","UA":"UKRAINE","AE":"UNITED ARAB EMIRATES","GB":"UNITED KINGDOM","US":"UNITED STATES","UM":"UNITED STATES MINOR OUTLYING ISLANDS","UY":"URUGUAY","UZ":"UZBEKISTAN","VU":"VANUATU","VE":"VENEZUELA, BOLIVARIAN REPUBLIC OF","VN":"VIET NAM","VG":"VIRGIN ISLANDS, BRITISH","VI":"VIRGIN ISLANDS, U.S.","WF":"WALLIS AND FUTUNA","EH":"WESTERN SAHARA","YE":"YEMEN","ZM":"ZAMBIA","ZW":"ZIMBABWE"};
    
    var parent   = $('#' + country_input_id).parent();
    var selected = $('#' + country_input_id).val();
    selected = jQuery.trim(selected);
    
    if(selected == '') {
    	selected = country_default;
    }
        
    $('#' + country_input_id).remove();

    parent.append('<select id="'+country_input_id+'" name="'+country_input_name+'"></select>');
    $.each(countries, function(key, value) {
    		if(key == selected) {
   		     $('#' + country_input_id).
	          append($("<option></option>").
	          attr("value",key).
	          attr("selected", 'selected').
	          text(value)); 	
    		} else {
   		     $('#' + country_input_id).
	          append($("<option></option>").
	          attr("value",key).
	          text(value));     			
    		}

	});
    
    states_change();
    
	/* bind country change */
	$('#' + country_input_id).bind('change', function() {
		states_change();
	});
}

function states_change() {
	/**
	 * a821 - Holds the country
	 * a820 - Holds the state
	 */
	var country = $('#' + country_input_id).val();
	var url = states_url + country;
	
	$.ajax({
		  url: url,
		  dataType: 'json',
		  success: function(json) {
			if(json && typeof(json.states) != 'undefined' && json.label != '') {
				var parent = $('#' + state_input_id).parent();
				var selected = $('#' + state_input_id).val();
				selected = jQuery.trim(selected);
				
				if(json.states) {
					$('#' + state_input_id).remove();
					/* update label */
					//$('label[for="'+state_input_id+'"]').text(json.label);
					

				    parent.append('<select id="'+state_input_id+'" name="'+state_input_name+'"></select>');
				    $.each(json.states, function(key, value) {
				    		if(value == selected) {
				   		     $('#' + state_input_id).
					          append($("<option></option>").
					          attr("value",value).
					          attr("selected", 'selected').
					          text(value)); 	
				    		} else {
				   		     $('#' + state_input_id).
					          append($("<option></option>").
					          attr("value",value).
					          text(value));     			
				    		}

					});
				}
			} else {
				var parent = $('#' + state_input_id).parent();
				var selected = $('#' + state_input_id).val();
				
				$('#' + state_input_id).remove();
				parent.append('<input type="text" value="'+selected+'" id="'+state_input_id+'" name="'+state_input_name+'">');
			}
		  }
	});
}

function update_supplier_subtypes() {
	var type = $('#supplier_type :selected').val();
	var subtype = subtypes[type];

	var selected = $('#ProfileProfileSubtype').attr('rel');
	/* clean select */
	$('#ProfileProfileSubtype').children().remove();
	
	$.each(subtype, function(key, value) {
		if(key == selected) {
		     $('#ProfileProfileSubtype').
          append($("<option></option>").
          attr("value",key).
          attr("selected", 'selected').
          text(value)); 	
		} else {
		     $('#ProfileProfileSubtype').
          append($("<option></option>").
          attr("value",key).
          text(value));     			
		}

	});
}


function add_affiliation() {
	var profile_id = $('#id').val();
	var affiliation = $('#affiliation :selected').text();
	
    $.ajax({
        url: '/affiliations/add_to_profile/' + profile_id,
        dataType: 'html',
        type: 'POST',
        data: {'id': profile_id, 'affiliation': affiliation },
        success: function() {
           $('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
        }
    });  	
}

function bind_affiliation_del() {
	$('div#affiliations a#remove').each(function() {
		$(this).bind('click', function() { affiliation_del($(this)); }); 
	});
}

function affiliation_del(me) {
	var profile_id = $('#id').val();
	var id = me.parent().attr('id').replace('affiliation', '');
	$.ajax({
        url: '/affiliations/del_from_profile/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
           $('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
        }
    });
}

function update_affiliations() {
	var profile_id = $('#id').val();
	$('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
}

function add_text_to_input(input_id, after, before) {
	var parent   = $('#'+input_id).parent();
	if(after != undefined) {
		parent.append(after);
	}
	
	if(before != undefined) {
		children = parent.children();
		children.each(function() {
			if($(this).is('input')) {
				$(this).before(before);
			}
		});
	}
}

function add_text_cakefield(cakefieldname, after, before) {
	var parent   = $('input[name="'+cakefieldname+'"]').parent();

	if(after != undefined) {
		parent.append(after);
	}
	
	if(before != undefined) {
		children = parent.children();
		children.each(function() {
			if($(this).is('input')) {
				$(this).before(before);
			}
		});
	}
}

function bind_certified(cakefieldname) {
	var fieldselector = "input[name='"+cakefieldname+"']:radio";
	var fields = jQuery(fieldselector);

    fields.each(function() {
        $(this).bind('change', function() { handle_certified(cakefieldname); });
    });
}

function handle_certified(cakefieldname) {
	var cert_fieldselector = cakefieldname.substring(cakefieldname, cakefieldname.length - 1);
	cert_fieldselector = cert_fieldselector + '_certified]';
	cert_fieldselector = "input[name='"+cert_fieldselector+"']:radio:first";
	
	var fieldselector = "input[name='"+cakefieldname+"']:radio";
	var fields = jQuery(fieldselector);

	fields.each(function() {
	    if($(this).attr('checked')) {
		    /* on Yes val => 1 show _cert field */
            var container = jQuery(cert_fieldselector).parent().parent();
            var val = parseInt($(this).val());
	        if(val) {
	            container.show('fast');
	            container.find('input').removeAttr('disabled');
	        } else {
		        container.hide('fast');
	            container.find('input').attr('disabled', 'disabled');
	        }
	    }
	});
}

function bind_children(parent_cakename) {
	var fieldselector = "input[name='"+parent_cakename+"']";
	var fields = jQuery(fieldselector);

    fields.each(function() {
        $(this).bind('change', function() { hide_children(parent_cakename); });
    });
}

function hide_children(parent_cakename) {
	var fieldselector = "input[name='"+parent_cakename+"']";
	var fields = jQuery(fieldselector);
	var parent = $(fieldselector).parent().parent();

	fields.each(function() {
	    if($(this).attr('checked')) {
		    /* on Yes val => 1 show _cert field */
            var container = parent.children('.subquestions');
            var val = parseInt($(this).val());
	        if(val) {
	            container.show('fast');
	            container.find('input').removeAttr('disabled');
	        } else {
		        container.hide('fast');
	            container.find('input').attr('disabled', 'disabled');
	        }
	    }
	});
}


function update_units(area_label_fields, units) {
	jQuery.each(area_label_fields, function(index, element) {
		var jquery_element = $('input[name="'+element+'"]');
		var parent   = $('input[name="'+element+'"]').parent();

		parent.children('.units').remove();
		parent.append('<span class="units">&nbsp; '+units+'</span>');
	});
}

/* tables fun */
function add_table() {
	var profile_id = $('#id').val();
	var affiliation = $('#affiliation :selected').text();
	
    $.ajax({
        url: '/affiliations/add_to_profile/' + profile_id,
        dataType: 'html',
        type: 'POST',
        data: {'id': profile_id, 'affiliation': affiliation },
        success: function() {
           $('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
        }
    });  	
}

function bind_affiliation_del() {
	$('div#affiliations a#remove').each(function() {
		$(this).bind('click', function() { affiliation_del($(this)); }); 
	});
}

function affiliation_del(me) {
	var profile_id = $('#id').val();
	var id = me.parent().attr('id').replace('affiliation', '');
	$.ajax({
        url: '/affiliations/del_from_profile/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
           $('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
        }
    });
}

function update_affiliations() {
	var profile_id = $('#id').val();
	$('#affiliations').load('/profiles/affiliations/' + profile_id, function() { bind_affiliation_del(); });
}

function bind_accommodations_del() {
    $('table#supplier-table a.supplier-remove').each(function() {
        $(this).bind('click', function() { accommodations_del($(this)); return false; }); 
    });
}

function accommodations_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    $.ajax({
        url: '/suppliers/del_accomodation_supplier/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
    	update_accomodations();
        }
    });

}

function bind_meetingvenues_del() {
    $('table#supplier-table a.supplier-remove').each(function() {
        $(this).bind('click', function() { meetingvenues_del($(this)); return false; }); 
    });
}

function meetingvenues_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    $.ajax({
        url: '/suppliers/del_meetingvenue_supplier/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
    		update_meetingvenues();
        }
    });

}


function bind_communication_del() {
    $('table a.supplier-remove').each(function() {
        $(this).bind('click', function() { communication_del($(this)); return false; }); 
    });
}

function communication_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    $.ajax({
        url: '/suppliers/del_communication_item/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
    		update_communication_items();
        }
    });

}

function bind_transportation_del() {
    $('table a.supplier-remove').each(function() {
        $(this).bind('click', function() { transportation_del($(this)); return false; }); 
    });
}

function transportation_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    $.ajax({
        url: '/suppliers/del_transportation_item/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
    		update_transportation_items();
        }
    });

}

/* comm&mkt */
function comm_mkt_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    console.log(id);
    $.ajax({
        url: '/suppliers/del_comm_mkt_item/' + id,
        dataType: 'html',
        type: 'GET',
        success: function() {
    		update_comm_mkt_items();
        }
    });

}

function bind_comm_mkt_del() {
    $('table a.supplier-remove').each(function() {
        $(this).bind('click', function() { comm_mkt_del($(this)); return false; });
    });
}

/* suppliers */
function bind_supplier_del() {
    $('table a.supplier-remove').each(function() {
        $(this).bind('click', function() { supplier_del($(this)); return false; }); 
    });
}

function supplier_del(me) {
    var id = me.parent().parent().attr('id').replace('supplier', '');
    $.ajax({
        url: '/suppliers/del/' + id,
        dataType: 'html',
        type: 'POST',
        success: function() {
    	     update_suppliers();
        }
    });
}

function help(){ 		
	$('.help img').qtip({
	position: { corner: { target: 'topMiddle', tooltip: 'bottomMiddle' }  },
	show: { when: { event: 'click' } },
	hide: { when: { event: 'click' } },	
	style: { border: { width: 2, radius: 5 },
			 padding: 5, textAlign: 'center', tip: true, name: 'cream' 
	},
	content: { text: false }    	         
	});
}	

function loading_spinner(div) {
	var img = new Image(16,16);
	img.id  = 'loading-div-spinner';
	img.src = '/img/facebox/loading.gif';
	img.style.cssFloat = 'left';
	img.style.margin = '2px 4px 2px 2px';
	img.style.verticalAlign = 'middle';
	
	var loader_div = document.createElement('div');
	loader_div.id = 'loading-div';
	loader_div.innerHTML = 'Saving...';
	loader_div.appendChild(img);
	loader_div.style.clear = 'both';
	
	$(div).prepend(loader_div);
}
