$(function () {
    initHorizontalScroller(),
//    initGetQuotes(),
    initLightbox(),
    initLiveHelp();
    initGetInformation();
    initUniversalFunctions();
});

function initUniversalFunctions()
{
    $("a.noclick").click(function(){
        return false;
    })
}

function initHorizontalScroller()
{
    var _controls = $(".prev-provider, .next-provider");
    var _s = $("#providers-holder ul"); // selector

    var _eachoffset = $("#providers-holder").width();
    var _left = 0;
    var _flagged = false;

    var _swidth = 0;
    $("#providers-holder ul li").each(function(){
        _swidth = _swidth + $(this).width();
    })
    _s.css("width", _swidth);

    if(_swidth > _eachoffset+10)
    {
        // CREATE CLICK SELECTOR
        _controls.click(function()
        {
            // original left logic
            //        _left = ($(this).hasClass("prev-provider")) ? ((_left+_eachoffset >= 0) ? 0 : (_left+_eachoffset)) : ((_left-_eachoffset <= _swidth*-1) ? _left : (_left-_eachoffset));

            _flagged = false;
            if($(this).hasClass("prev-provider"))
            {
                // IS PREV
                if(_left+_eachoffset > 0)
                {
                    _left = 0;
                    _templeft = _left+130;
                    _flagged = true;
                    // hide prev arrow
                } else {
                    _left = _left+_eachoffset;
                }

            } else {
                // IS NEXT
                if(_left-_eachoffset <= _swidth*-1)
                {
                    // left doesnt change
                    // hide next arrow
                    _templeft = _left-130;
                    _flagged = true;

                } else {
                    _left = _left-_eachoffset;
                }
            }

            if(_flagged === true)
            {
                // show user we're at the end of the slides by faking the animation and animating back'
                _s.animate({
                    "left" : _templeft
                  }, {
                    duration: 250,
                    specialEasing: {
                      left: 'jswing'
                    },
                    complete: function() {
                          _s.animate({
                            "left" : _left
                          }, {
                            duration: 500,
                            specialEasing: {
                              left: 'jswing'
                            }
                          }); // end animation
                    }
                  }); // end animation



            } else {
                // default slide action
                _s.animate({
                    "left" : _left
                  }, {
                    duration: 650,
                    specialEasing: {
                      left: 'jswing'
                    }
                  });
            }
            return false; // kill default behavior for link click
        }).show();
    }
    
}

function initGetQuotes()
{
    var _v = getCookie('exp_mc2_details');

    if(_v == null)
    {
        $("#getaquote").submit(function(){
            var brokerName = "Thank you for visiting Medicare65.com";
            var brokerPhone = "Please call us with any questions or to apply today at: 1-800-247-9889";
            var ok = true;
            var qsZip = document.getElementById('txtZip').value;
                    var qsAge = document.getElementById('txtAge').value;
                    rGender = document.getElementsByName("txtGender");
                    for(var i = 0; i < rGender.length; i++) {
                            if (rGender[i].checked) { qsGender = rGender[i].value;}
                    }
                    qsSmoker = 'N';
                    if (document.getElementById('txtAppSmoker').checked) {qsSmoker = 'Y'};

            reZip = /^[0-9]{5}$/;
            if (!qsZip.match(reZip)) {
                    alert("Please enter a valid Zip Code.");
                    document.getElementById('txtZip').focus();
                    document.getElementById('txtZip').select();
                    ok = false;
                            return false;
            }
                    reAge = /^[0-9]{2}$/;
                    if (!qsAge.match(reAge)) {
                    alert("Please enter Age.");
                    document.getElementById('txtAge').focus();
                    document.getElementById('txtAge').select();
                    ok = false;
                            return false;
            }
            if (ok == true) {
                    var sPath = 'http://www.medicaresolutions.com/planlistmedicare_widget.asp?zip=' + qsZip + '&broker=' + brokerName + '&phone=' + brokerPhone + '&age=' + qsAge + '&gender=' + qsGender + '&smoker=' + qsSmoker;
                    var winProp;
                    winProp ='top=100,left=100,height=650,width=850,resizable=yes,scrollbars=yes,titlebar=no,status=no,toolbar=no,menubar=no,location=no';
                    window.open(sPath,'',winProp);
            }
        })
    }

    
}
function initLightbox()
{
//    $("a.lightbox").colorbox({iframe:true, width:"60%", height:"60%"});
//    $(window).scroll(function () {
//        $.fn.colorbox.resize({width:"60%", height:"60%"});
//    });
    $("a.lightbox").colorbox();
}

function initLiveHelp()
{
    $("#medicare-help a, #medicare-help-offline a").click(function(){
        _alc.startChat(14747);
        return false;
    })
}

function initGetInformation()
{
    $("#intake").submit(function()
    {
        $errorflag = false;
        if ($("#name").val().length != 0) { $("#name").removeClass("error") } else { $("#name").addClass("error"); $errorflag = true; }
        if (zipcodeValidate($("#txtZip").val()) == true) { $("#txtZip").removeClass("error") } else { $("#txtZip").addClass("error"); $errorflag = true; }
        if (emailValidate($("#txtEmail").val()) == true) { $("#txtEmail").removeClass("error") } else { $("#txtEmail").addClass("error"); $errorflag = true; }
        if (phoneValidate($("#txtPhone").val()) == true) { $("#txtPhone").removeClass("error") } else { $("#txtPhone").addClass("error"); $errorflag = true; }
        if ($("#age").val().length != 0) { $("#age").removeClass("error") } else { $("#age").addClass("error"); $errorflag = true; }

        if ($errorflag != true)
        {
            $age = $("#age").val();
            $age = ($age > 64 && $age < 90) ? $age : ($age == "turning65" || $age == "under63") ? 65 : ($age == "90plus") ? 90 : 65;

            var a = [{
                    "name" : $("#name").val(),
                    "zip" : $("#txtZip").val(),
                    "phone" : $("#txtPhone").val(),
                    "email" : $("#txtEmail").val(),
                    "age" : $age,
                    "gender" : $("#gender").val(),
                    "tobacco" : $("#tobacco").val()
            }];
            
            directQuote(a);
            
            return true;
        }
        return false;
    });

//    function getQuote(_z,_a,_g,_s)
//    {
//        var brokerName = "Thank you for visiting Medicare65.com";
//        var brokerPhone = "Please call us with any questions or to apply today at: 1-800-247-9889";
//
//        var sPath = 'http://www.medicaresolutions.com/planlistmedicare_widget.asp?zip=' + _z + '&broker=' + brokerName + '&phone=' + brokerPhone + '&age=' + _a + '&gender=' + _g + '&smoker=' + _s;
//        var winProp;
//        winProp ='top=100,left=100,height=650,width=850,resizable=yes,scrollbars=yes,titlebar=no,status=no,toolbar=no,menubar=no,location=no';
//        window.open(sPath,'',winProp);
//    }
    function directQuote(a)
    {
//        ?name=Jarrett Barnett&zip=93010&phone=5301111111&email=jarrett@mc2design.com&age=65&gender=M
        var _qs = "";
        $.each(a[0], function(key, value)
        {
            _qs = _qs + key + "=" + escape(value) + "&";
        });
        _qs = _qs.slice(0,-1);

        var path = "http://www.medicare65.com/forms/directquote/index.php?" + _qs;
        var winProp = 'top=100,left=100,height=650,width=850,resizable=yes,scrollbars=yes,titlebar=no,status=no,toolbar=no,menubar=no,location=no';
        window.open(path,'',winProp);
    }

    function zipcodeValidate(_zip)
    {
        var _valid = "0123456789-";

        if(_zip.length == 5) {
            for (var i=0; i < _zip.length; i++) {
                _temp = "" + _zip.substring(i, i+1);
                if (_valid.indexOf(_temp) == "-1") return false;
            }
            return true;
        } else {
            return false;
        }
    }

    function emailValidate(str, _cb)
    {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }

		 if (str.indexOf(" ")!=-1){
		    return false
		 }

                 if(_cb) this._cb();
 		 return true
	}

        function ValidateForm() {
            var emailID=document.frmSample.txtEmail

            if ((emailID.value==null)||(emailID.value=="")){
                    alert("Please Enter your Email ID")
                    emailID.focus()
                    return false
            }
            if (echeck(emailID.value)==false){
                    emailID.value=""
                    emailID.focus()
                    return false
            }
            return true
         }

         function phoneValidate(_phone)
         {
            _phone = _phone.replace(/[^0-9]/g, '');
            if(_phone.length !== 10) {
               return false; // display message about  area code
            } else {
              return true;
            }

         }


    
}

function getCookie( cookie_name ) {
	// first we'll split this cookie up into name/value pairs
	// document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	var newcookie = '';

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// splits apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trims whitespace on the left and right of the value
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the cookie name matches the requested cookie
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// check whether found cookie has no value so we can return null if neccesary
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// return the cookie and stop script if value exists, otherwise, continue
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
