email_re = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

var sep = ".";

function formatCurrency(inpObj) {
       inpValue = inpObj.value;
       var fromIndex = 0;
       var toIndex = 0;
       ytlVal = inpValue;
       var unformattedString = deCommafy(ytlVal) ;
       if ( unformattedString.length > 9 ) {
           unformattedString = unformattedString.substring(0,9);
       }
       if ( !isNaN( parseInt(unformattedString,10) ) ) {
           unformattedString = parseInt(unformattedString,10).toString() ;
       } else {
           inpObj.value = "";
           inpObj.focus();
           return;
       }
       inpObj.value = commafy( unformattedString );
}

function deCommafy(inpValue) {
       var re = eval("/\\" + sep + "/g") ;

       return inpValue.replace(re,"");
}

function commafy(inpValue) {
       var re = /(\d+)(\d{3})/ ;
       while ( re.test(inpValue) ) {
           inpValue = eval("inpValue.replace(re,'$1" + sep + "$2')");
       }
       return inpValue;
}

function tckimlikkontorolu(tcno)	
{
	if (tcno.value.length!=11)	
	{
		return false;
	}
	var tckontrol,toplam; 
	tckontrol = tcno; 
	tcno = tcno.value;
	toplam = Number(tcno.substring(0,1)) + Number(tcno.substring(1,2)) + Number(tcno.substring(2,3)) + Number(tcno.substring(3,4)) + Number(tcno.substring(4,5)) + Number(tcno.substring(5,6)) + Number(tcno.substring(6,7)) + Number(tcno.substring(7,8)) + Number(tcno.substring(8,9)) + Number(tcno.substring(9,10));
	strtoplam = String(toplam); 
	onunbirlerbas = strtoplam.substring(strtoplam.length, strtoplam.length-1);
	if(onunbirlerbas == tcno.substring(10,11)) 
	{
		return true;
	}
	else	
	{
		return false; 
	}
}

function showOverlay(cont_elm_id)	{
	if (cont_elm_id == null)	{
		$.blockUI({ 
			overlayCSS: { 
				backgroundColor: '#419107',
				opacity: .2 
			},
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
			forceIframe: true,
			quirksmodeOffsetHack: 4,
			message: "<h1 style='padding:0;color:#3366CC;font-family:arial,Verdana;font-size:18px;font-weight:bold;'>"
				+"<div style='padding-bottom:5px;'><img src='"+ROOT+"img/v2/loading.gif'/></div><div>Sigorta priminiz hesaplanıyor, lütfen bekleyin...</div>"
				+"</h1>",
		    css: {
				padding: "15px 0 0"
			}
		});
	}
	else	{
		$('#'+cont_elm_id).block({
			overlayCSS: {
			backgroundColor: '#419107',
			opacity: .2
		},
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',
				forceIframe: true,
				quirksmodeOffsetHack: 4
		});
	}
}

function hideOverlay(cont_elm_id)	{
	if (cont_elm_id != null)
		$('#'+cont_elm_id).unblock();
	else
		$.unblockUI();
}

function prepareHealthInsuranceForm()	{
	$.blockUI.defaults.applyPlatformOpacityRules = false;
    $.blockUI.defaults.css = {};
    
	_wife = 0;
	_children = 0;
	
	$("select[name=marital_status]").change(function(e){
        if (this.value == 2)    {
            $(this).parent().next().show();
            $(this).parent().next().next().show();
        }
        else if (this.value == 3 || this.value == 4)    {
        	$(this).parent().next().next().show();
        	$(this).parent().next().hide();
        }
        else    {
        	$(this).parent().next().next().hide();
        	$(this).parent().next().hide();
        }
    });

    $("select[name=children_count]").change(function(e){
    	$("select[name=children_included] option").show();
    	$("select[name=children_included]").val(0);
        if (this.value > 0)    {
            $("select[name=children_included] option:value:gt("+this.value+")").hide();
            $("select[name=children_included]").val(this.value);
            $(this).parent().next().show();
        }
        else    {
            $(this).parent().next().hide();
            $("select[name=children_included]").val(0);
        }
    });

    $(".base_person[type=self] select[name=gender]").change(function(e){
    	if ($(".base_person[type=wife]").is(":exist")) {
    	    if (this.value == "m") {
    	    	$(".base_person[type=wife] select[name=gender]").val("f");
    	    }
    	    else if (this.value == "f") {
                $(".base_person[type=wife] select[name=gender]").val("m");
            }
    	}
    });

    $("#step1_submit").click(function(e){
        e.preventDefault();

        if ($.trim($("input[name=first_name]").val()).length == 0)  {
            alert("Lütfen adınızı girin.");
            $("input[name=first_name]").focus();
            return false;
        }
        if ($.trim($("input[name=last_name]").val()).length == 0)  {
            alert("Lütfen soyadınızı girin.");
            $("input[name=last_name]").focus();
            return false;
        }
        if (!email_re.test($("input[name=email]").val()))  {
            alert("Lütfen geçerli bir e-posta adresi girin.");
            $("input[name=email]").focus();
            return false;
        }
        if ($('input[name=mobile_area]').val().length!=3) {
            alert('Lütfen size ulaşabilmemiz için cep telefonu numarasınızı girin.');
            $("input[name=mobile_area]").focus();
            return false;
        }
        if ($('input[name=mobile_phone]').val().length!=7) {
            alert('Lütfen size ulaşabilmemiz için cep telefonu numarasınızı girin.');
            $("input[name=mobile_phone]").focus();
            return false;
        }
        if ($('input[name=mobile_area]').val().substring(0,1) != 5)   {
            alert('Lütfen geçerli bir cep telefonu numarası girin.');
            $("input[name=mobile_area]").focus();
            return false;
        }
        if ($('select[name=marital_status]').val() == 0)   {
            alert('Lütfen medeni halinizi seçin.');
            $("select[name=marital_status]").focus();
            return false;
        }
        if ($('select[name=marital_status]').val() == 2 && $('select[name=wife_included]').val() == 0)   {
            alert('Lütfen "Eşinizi sigorta kapsamına almak ister misiniz?" alanını seçin.');
            $("select[name=marital_status]").focus();
            return false;
        }

        $(".base_person:[type^=child], .base_person:[type=wife]").remove();
        _wife = _children = 0;
        
        if ($("select[name=wife_included]").is(":visible") && $("select[name=wife_included]").val() == 1) {
            _wife = 1;
        }

        if ($("select[name=children_included]").is(":visible") &&
            $("select[name=children_included]").val() > 0
        ) {
            _children = parseInt($("select[name=children_included]").val());
        }

        if (_wife == 1) {
        	_clone = $(".base_person:first").clone();
        	_clone.find("div.label").html("Eşiniz: ");
        	_clone.attr("type", "wife");
        	$(".base_person:last").after(_clone);
        }

        if (_children > 0)  {
            for (i=1; i<=_children; i++) {
            	_clone = $(".base_person:first").clone();
                _clone.find("div.label").html(i+". Çocuk: ");
                _clone.attr("type", "child"+i);
                $(".base_person:last").after(_clone);
            }
        }
        
        //$("#step1").slideUp("fast", function(){
        //	$("#step2").slideDown("normal");
        //});
        
        $("#step2").show();
        $('html, body').animate({
			scrollTop: $("#step2").offset().top
		}, 1000);
    });

    $("#step2_submit").click(function(e){
        e.preventDefault();

        _valid = true;
        $(".base_person").each(function(){
            age = $(this).find("input[name=age]").val();
            if (age == '' || age > 70 || age < 0)   {
            	_valid = false;
                alert("Yaş aralığı 0-70 yaşları arasında olmalıdır.");
                return false;
            }
            if ($(this).find("select[name=gender]").val() == 0) {
            	_valid = false;
            	alert("Lütfen cinsiyet alanlarını seçin.");
                return false;
            }
        });

        if (_valid == false) return false;
        
        params = {
            "form_id": form_id, "first_name": $("input[name=first_name]").val(),
            "last_name": $("input[name=last_name]").val(),
            "email": $("input[name=email]").val(),
            "mobile_phone": $("input[name=mobile_area]").val() + $("input[name=mobile_phone]").val(),
            "marital_status": $("select[name=marital_status]").val()
        };

        $("#step2 div.line").each(function(){
            if ($(this).attr("type") == "self") {
                params["sa"] = $(this).find("input[name=age]").val();
                params["sg"] = $(this).find("select[name=gender]").val();
            }
            else if ($(this).attr("type") == "wife") {
                params["wa"] = $(this).find("input[name=age]").val();
                params["wg"] = $(this).find("select[name=gender]").val();
            }
            else {
                params["ca"+$(this).attr("type").substr(5, 1)] = $(this).find("input[name=age]").val();
                params["cg"+$(this).attr("type").substr(5, 1)] = $(this).find("select[name=gender]").val();
            }
        });

        $.ajax({
        	type: "POST",
            url: ROOT+"sigorta/calc-health-ins",
            data: params,
            error: function(){
        		alert("Bir hata meydana geldi.");
        		hideOverlay(null);
    		},
            beforeSend: function(){
            	showOverlay(null);
            },
            success: function(data){
            	hideOverlay(null);
                $("#step3").html(data).show();
                $('html, body').animate({
        			scrollTop: $("#step3").offset().top
        		}, 1000);
            }
        });
    });

    $(".apply img").live("click", function(e){
        package_code = this.alt;

        $.ajax({
            type: "POST",
            url: ROOT+"sigorta/ajax-application?nossl=1",
            data: {"form_id": form_id, "form_type": 6, "package_code": package_code},
            error: function(){
        		alert("Bir hata meydana geldi.");
        		hideOverlay(null);
    		},
            beforeSend: function(){
    			showOverlay(null);
    		},
            success: function(data){
    			document.location.href = ROOT+"saglik-sigortasi/basvuru-onay";
            }
        });
    });
}
