var $fields;
var new_call_id;
var last_call_id;
var first_callback = true;

var output_msg = "";

function postToFeed() {
	
	var obj = {
		method: 'feed',
		message: 'Just played a prank on my friend and it was mad funny. Thanks to CallerIDFaker \m/',
		link: 'https://calleridfaker.com',
		picture: 'http://calleridfaker.com/media/images/phone-cartoon.png',
		name: 'CallerIDFaker',
		caption: 'The name says it all',
		description: 'Visit http://calleridfaker.com to fake your Caller ID and play pranks on your friends'
	};
	
	FB.ui(obj);
}

function start_check_for_free_call()
{
    cfc = function()
    {
        $.getJSON("/api/guid/calls/from/0/for/1/desc/?guid=" + guid + "&rnd=" + Math.random(),
        function (data)
        {
            if (data.calls[0] != null)
            {
                new_call_id = data.calls[0].callid;
                if (new_call_id != last_call_id)
                {
                    if (first_callback)
                    {
                        first_callback = false;
                    } else {
                        $("#sharemessages").html("<center><a onclick='postToFeed(); return false;' style='cursor:pointer;'><img src=\"/media/images/share_fb.png\" border=\"0\"></a> &nbsp; &nbsp; <a href=\"account/call/" + new_call_id + "/\"><img src=\"/media/images/share_call.png\" border=\"0\"></a></center>"); 
						
						
                    }
                }
                last_call_id = new_call_id;
            } else {
                first_callback = false;
            }
            setTimeout(cfc, 5000);
        });
    }
    cfc();
}



var dummycount = 0;

function start_check_for_paid_call()
{
    cfc = function()
    {
        $.getJSON("/api/" + pin + "/calls/from/0/for/1/desc/?guid=" + guid + "&rnd=" + Math.random(),
        function (data)
        {
            if (data.calls[0] != null)
            {
                new_call_id = data.calls[0].callid;
                if (new_call_id != last_call_id)
                {
                    if (first_callback)
                    {
                        first_callback = false;
                    } else {
                        $("#sharemessages").html("<center><a onclick='postToFeed(); return false;'><img src=\"/media/images/share_fb.png\" border=\"0\"></a> &nbsp; &nbsp; <a href=\"/account/call/" + new_call_id + "/\"><img src=\"/media/images/share_call.png\" border=\"0\"></a></center>");
						
						
                    }
                }
                last_call_id = new_call_id;
            } else {
                first_callback = false;
            }
            
            /*dummycount = dummycount + 1;
            //if(dummycount%100 == 0)
                $("#sharemessages").html(dummycount);
            if(dummycount == 10)
            { $("#sharemessages").html("<center><a href=\"/account/call/" + new_call_id + "/\"><img src=\"/media/img/continue_img.gif\" border=\"0\"></a></center>"); } */
            
            setTimeout(cfc, 5000);
        });
    }
    /*dummycount = dummycount + 1;
    //if(dummycount%100 == 0)
        $("#sharemessages").html(dummycount);
    if(dummycount == 10)
    { $("#sharemessages").html("<center><a href=\"/account/call/" + new_call_id + "/\"><img src=\"/media/img/continue_img.gif\" border=\"0\"></a></center>"); }  */
    cfc();
}

function load_form() {
  $fields.each(function(){
    var love = $.cookie('last_call_' + $(this).attr('name'));
    if (love)
      $(this).val(love);
  });
}

function save_form() {
  $fields.each(function(){
    $.cookie('last_call_' + $(this).attr('name'), $(this).val());
  });
  //alert("form saved");
}

$(document).ready(function(){
	
	$fields = $("#webcall :input");
	load_form();
	
	$("#webcall").submit(function() {
		$fields.css("background", "")
			   .css("color", "")
			   .css("font-weight", "");
		//var data = this.elements;
		
		$("#sharemessages").html("<center><h2>Once you hang up, your Call Link will appear here...</h2></center>");
		
		var my_phoneno = ""; var phoneno = ""; var cid = "";
		
		if(window.is_free_user){
			my_phoneno = $("#id_my_phoneno_number").val()+'';
			phoneno = $("#id_phoneno_number").val()+'';
			cid = $("#id_cid_number").val()+'';
		}else{
			my_phoneno = '%2b'+$("#id_my_phoneno_ccode").val()+''+$("#id_my_phoneno_number").val()+'';
			phoneno = '%2b'+$("#id_phoneno_ccode").val()+''+$("#id_phoneno_number").val()+'';
			cid = '%2b'+$("#id_cid_ccode").val()+''+$("#id_cid_number").val()+'';
		}		
		
		var senddata = $(this).serialize()+"&my_phoneno="+my_phoneno+"&phoneno="+phoneno+"&cid="+cid;
		
		$.ajax({
		  type:     "GET",
		  url:      api_url,
		  dataType: "json",
		  data:      senddata,
		  success:  function(json) {
			/*alert(json.access_number_pretty);
			$("#success span.dialinnumber").html("");
			document.getElementById('success').style.display = "none";
			document.getElementById('error').style.display = "none";     */     
			if (json.is_error) {
			  field = ("field" in json) ? $("#id_" + json.field) : $("#id_phoneno");
			  field.qtip({content: json.message, effect: {type: 'fade'}, show: {ready: true, effect: {type: 'fade', length: 500}},
						  hide: {when: {target: field, event: 'unfocus'}},
						  style: {name: 'red', tip: true, border: {width: 2, radius: 5}},
						  position: {corner: {target: 'topMiddle', tooltip: 'bottomMiddle'}}});
			} else {
			  centerPopup();
			  loadPopup();
			  $("span.dialinnumber").html(json.access_number_pretty);
			  //document.getElementById('success').style.display = "";
			  save_form();
			}
		  }
		});
		return false;
	});
  
	$("a.make-call").click(function(){
	
		var proceed = true;
		
		$(".call-field").each(function(index){
			var e = $(this);
			
			if($(e).val() == $(e).attr('alt')) {
				$(e).validationEngine('showPrompt', 'This field is required!', 'fail', true);
				proceed = false;
			}
		
		});
	
		if(proceed) {
			//$(".make-call").colorbox({width:"50%", height:"450px", inline:true, href:"#popupWebCall"});
			$("#webcall").submit();
		}
	});
	
});

function clean_phone(pn_field)
{
    matcher = new RegExp(pn_field.value, /\(?([0-9]{3})\)?-?([0-9]{3})-?([0-9]{4})/);
    matched = matcher.exec();
    new_num = matched[0] + "-" + matched[1] + "-" + matched[2];
    pn_field.value = new_num;
}

