jQuery(document).ready(function($) {
	//Show Teleform
	$('#btn_call, .btn_call').click(function() {
		display_teleform(this);
		click_tracker(1); //Dev_clks_tracker
	});
	
	//Hide Teleform
	$('#tbl_teleform #tlfrm_header #close').click(function () {
		hide_teleform();
	});
	
	//Set country code
	$('#countries').change(function () {
		set_country_code('#countries', '#Hdialcode');
	});
	
	//Make logo clickable
	$('#tbl_teleform #tlfrm_header .logo').click(function() {
		window.location.href = '/';
	});
	
	//Start Call
	$('#tlfrm_call').click(function() {
		//Mix Hdialcode and phone
		if ($('#tlfrm_phone').val() != '') {
			var phone = $('#Hdialcode').val() + $('#tlfrm_phone').val();
		} else if ($('#tlfrm_phone').val() == '111') {
			var phone = $('#Hdialcode').val() + $('#tlfrm_phone').val();
		} else {
			$('#tbl_teleform #tlfrm_results').html('<div class="error">Phone number is invalid!</div>').fadeIn('slow');
		}
		
		//Initialize call function
		trigger_call(phone);
		
		click_tracker(2, phone); //Dev_clks_tracker
	});
});

/*** FUNCTIONS ***/
function display_teleform(e) {
	var teleform = $('#teleform_wrapper'); //Teleform main container
	var drag_id_class =  $('#tlfrm_header'); //ID/Class the teleform will be dragable
	var offset = $(e).offset();
	var position = $(e).position();
	
	//Reposition the teleform, slowly fade it in and make it dragable by header.
	teleform.css({ 'top': position.top, 'left': position.left }).fadeIn('slow').jqDrag(drag_id_class);
}

function hide_teleform() {
	$('#teleform_wrapper').fadeOut('fast');
}

function trigger_call(phone, did) {
	$('#tbl_teleform #tlfrm_results').html('<br /><div><img src="/images/loadingAnimation.gif" alt="loading..." /></div>').fadeIn('slow');
	
	var did = '';
	var uid = $('#instafon_id').val();
	//Launch API
	$.ajax({
		type: "POST",
		url: "/dev_main_handler.php",
		data: "action=call&phone="+phone+'&did='+did+'&uid='+uid,
		success: function(msg) {
			$('#tbl_teleform #tlfrm_results').html(msg).fadeIn('slow');
		}
	});
}

function set_country_code(countries, Hdialcode) { $(Hdialcode).val($(countries).val()); }

function onlyNumeric(event) {
	var strUserAgent = navigator.userAgent.toLowerCase();
	var isIE = strUserAgent.indexOf("msie") > -1;
	
   if(isIE) {
   	iKeyCode = event.keyCode;
   } else {
   	iKeyCode = event.which;
   }
   if((iKeyCode >= 32 && iKeyCode <= 43) || (iKeyCode == 45 || iKeyCode == 44 || iKeyCode == 47) || iKeyCode >= 58) {
   	return false;
   }
   return true;
}

/*** CLICK TRACKER ***/
function click_tracker(event_id, phone) {
	$.ajax({
		type: "POST",
		url: "/dev_main_handler.php",
		data: "action=click&eid="+event_id+'&phone='+phone,
		success: function(msg) {
			//alert(msg);
		}
	});
}