/* Zipcar Global Javascript Functions

By Will Moore and friends  - ISITE Design


*/

var cities = [];
var city_matches = [];
var hybrid_matches = [];
var city_ids = [];
var extra_url_vars;
var initial_url_vars;

var opacity = 40;

var geocoder;
var geotimer;
var match_indices;
var matches;
var overlay = opacity;

//start the jQuery functions
$(document).ready(function() {


	 //apply automatic input clearing to the search input - add as needed
	$("#searchform input, #birthdate-year, #license_expiration_year").inputClear();

	// alternate version of the above plugin that pulls the label, sets as the input's default value and hides it.  so clever.
	$("#searchform input, #notify-new-locations input, #gmaps-search input, #location-search, #company-search, #univ-search, .company-search").inputSetter();

	// add class to replicate :hover for non a elements.  For drop downs and buttons for IE<=6.  Silly IE6.
	if(document.all && !window.XMLHttpRequest){
	    $("#nav li, button, .nav-page li, .gbtn").hover(
	            function() {
					$(this).addClass("over");
				},
	            function() {
					$(this).removeClass("over");
				}
	    );
        $(".gbtn, .tbtn").hover(
	            function() {
					$(this).addClass("gbtn_over");
				},
	            function() {
					$(this).removeClass("gbtn_over");
				}
        );
	    $(".png-btn").hover(
	            function() {
					$(this).addClass("png-btn-over");
				},
	            function() {
					$(this).removeClass("png-btn-over");
				}
	    );
	}// if document.all

	//locations toggle.  Note: Hide this sorta stuff with js, not css, in case js is disabled.
	// note too, we're adding the class "js-on" to the revealed boxes so we can style and position the js version differently
	// There is a bug with IE6/7 that forces the content in the footer down when this is revealed.  We're using js to move it up in the source order.
	$("#where_are_cars").hide().addClass("js-on").prepend("<a href='#' class='close jqmClose'>close</a>");

    $("#where_are_cars a.close").click(function () {
        $('#where_are_cars_wrapper').jqmHide();
    });

	$("#where_are_cars h3.nojsfriendly").hide();
	$("#locations-toggle").click(function(){
		// $("#where_are_cars").slideToggle(300)
        var wacw = $('#where_are_cars_wrapper');
        // having this overlay set to something > 0 seems to prevent firefox
        // rendering bug where background image appears to smear during slide down
        if (overlay > 1) {
            overlay = 1;
            wacw.jqmShow();
        } else {
            wacw.jqmHide();
        }
		return false;
	});


//		// inner univerities listing show/hide.  we're setting the text of the span via js so that when there's no js present,
//		// we don''t have meaningless text on the page about toggling.  instead we just have a heading for the list.
//		// same with the little arrow - added via class="open/closed" here in the js.
//       	$("#where_are_cars h3 span").show().addClass("open").text("expand to see");
//		$("#where_are_cars .universities").hide();
//		$("#where_are_cars h3.toggle-uni").toggle(
//			function () {
//				$("#where_are_cars .universities").slideDown(200);
//				$(this).find("span").addClass("closed").removeClass("open").text("collapse to hide");
//
//			},
//			function () {
//				$("#where_are_cars .universities").slideUp(200);
//				$(this).find("span").addClass("open").removeClass("closed").text("expand to see");
//			});


	// sign up form for notify inside of locations drop down
	$("#notify-new-locations").addClass("click-me").hide();
	$("#notify-new-locations").prev().addClass("click-me").click(function(){
		$("#notify-new-locations").toggle();
	});


	//show hide the login form
	$("#sign-in").addClass("js-on").hide()
	$("#sign-in").prepend("<a href='#' class='close'>close</a>")
	$("#sign-in .close").click(function(){
			$("#sign-in").slideToggle(200);
			$("#signin-trigger").toggleClass("active")
			return false;
	});
	$("#signin-trigger").click(
		function(){
			$("#sign-in").slideToggle(200, function() {
                $("#sign-in #user_name").focus();
            });
			$(this).toggleClass("active")
			return false;
   		}
	);


    try {
        //Did you know? content flipper
        $("#did-you-know .container ").jCarouselLite({
            btnNext: "#did-you-know .prev",
            btnPrev: "#did-you-know .next",
            visible: "1",
            speed:   425
        });
    } catch (e) {};

	// add class "last" to the last li in any list.  Used as a styling hook since :last-child isn't widely supported via css.  thank you jquery.
    $("ul li:last-child").addClass("last");

    /*
    add <a>s with class "vertical-more"  to your page, give each one an id
    then on the hidden "more" element add the class "vertical-more-info" and the id of the <a>
    */
    $(".vertical-more").click(function () {
        var toggleId = $(this).attr("id");
        //console.log("toggleId: " + toggleId + " IcanhazClass: " + $(this).hasClass("vertical-more-on"));
        var pseudoId = "." + toggleId;

        if ($(this).hasClass("close-others")) {

            $(".vertical-more-info").hide(300);

            if ($(this).hasClass("vertical-more-on")) {
                $(this).removeClass("vertical-more-on");
                $(pseudoId).slideUp(300);
            } else {
                $(pseudoId).slideDown(300);
                $("a.vertical-more").removeClass("vertical-more-on");
                $(this).addClass("vertical-more-on");
            }

        } else {
            $(this).toggleClass("vertical-more-on");
            $(pseudoId).slideToggle(300);
        }
        
        return false;
        
    });

});// document ready / end jquery functions


/* clear search field on click - made into plugin so it can easily be used more than once. */
jQuery.fn.inputClear = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};

// alternate version of the above. pull label and insert as field. clear with click.
jQuery.fn.inputSetter = function() {

	return this.each(function() {

		var $input = $(this);
		var $label = $("label[for='"+$input.attr("id")+"']");
		var labeltext = $label.text();

		$label.hide();
		$input.val(labeltext);

		$input.focus(function() {
			if (this.value == labeltext) {
				this.value = "";
			}
		}).blur(function() {
			if (!this.value.length) {
				this.value = labeltext;
			}
		});

	});
};


// clean console.log.  Wont break IE6 if you leave it in your code.  cl("stuff to log")
function cl(logit){ if(window.console&&window.console.firebug) { console.log(logit) } };//cl()




/*
 * basic function to work around people double clicking on submit buttons
 **/
var dblClickPreventer = new Object();
dblClickPreventer.ids = new Array();
dblClickPreventer.onclick = function( evt, perm ) {
    if( !evt ) evt = window.event;
    var ele = ( evt.target ? evt.target : evt.srcElement );
    var key = ele.tagName + "#" + ele.id + "#" + ele.name + "#" + ele.type + "#" + ele.value;
    
    if( perm ) {
        if( !dblClickPreventer.ids[ key ] ) {
            dblClickPreventer.ids[ key ] = true;
            return true;
        } else {
            return false;
        }
    } else {
        var oldVal = dblClickPreventer.ids[ key ];
        var newVal = (new Date()).getTime();
    
        if( !oldVal || ( newVal - oldVal > 1000 ) ) {
            dblClickPreventer.ids[ key ] = newVal;
            return true;
        } else {
            return false;
        }
    }
}

// function to wrap google analytics to avoid going to "false" in anchor tags
function trackEvent(category, action, optional_label, optional_value) {
    if (optional_label == null || optional_label == undefined) {
        optional_label = ga_subpage;
    }
    if (optional_value != null && optional_value != undefined) {
        optional_value = parseInt(optional_value);
    }
    pageTracker._trackEvent(category, action, optional_label, optional_value);
}

//namespace
var zc = (function() {
        
    return {};
    
})();


//credit card related Javascript
zc.cc = (function() {
   return {
       verisign_checksum : function( num ) {
        
        
        //clean whitespace
        num = num.replace( "\s", "" );
        
        var first2 = num.slice(0,2);
        var first3 = num.slice(0,3);
        var first4 = num.slice(0,4);
        var first6 = num.slice(0,6);
        var len = num.length;
        var type = "unknown";
        
        if( num[0] == "4" && ( len == 13 || len == 16 ) )
            type = "VISA"
        
        switch( first2 )
        {
            case "65": 
                if( len == 16)
                    type = "Discover";
                break;
            case "36": 
            case "38": 
                if( len == 14 )
                    type ="Diner's Club / Carte Blanche";
                break;
            case "34": 
            case "37": 
                if( len == 15 )
                    type = "American Express";
                break;
            case "51": 
            case "52": 
            case "53": 
            case "54": 
            case "55": 
                if( len == 16 )
                    type = "MasterCard";
                break;

        }
        
        switch( first3 )
        {
            case "300": 
            case "301": 
            case "302": 
            case "303": 
            case "304": 
            case "305": 
                if( len == 14 )
                    type ="Diner's Club / Carte Blanche";
                break;
        }
        
        var first4num = parseInt( first4 );
        if( first4num >= 3528 && first4num <= 3589 && len == 16 )
        {
            type = "JCB"
        }

        switch( first4 )
        {
            case "5020": 
            case "5038": 
            case "6759": 
            case "4903": 
            case "4905": 
            case "4911": 
            case "4936": 
            case "6333": 
            case "6759": 
                if( len == 16 || len == 18 || len == 19 )
                    type = "Maestro";
                break;
            case "6334": 
            case "6767": 
                if( len == 16 || len == 18 || len == 19 )
                    type = "Solo";
                break;
            case "4508": 
            case "4917": 
            case "4844": 
                if( len == 16 )
                    type ="Visa Electron";
                break;
            case "6011": 
                if( len == 16)
                    type = "Discover";
                break;
            case "2014": 
            case "2149": 
                if( len == 15 ) {
                    type = "enRoute";
                    
                    //early exit for enRoute
                    return type;
                }
                break;
            case "5610":
                if( len == 16 )
                    type = "Australian BankCard";
                break;
        }   
        
        switch( first6 )
        {
            case "564182": 
            case "633110": 
                if( len == 16 || len == 18 || len == 19 )
                    type = "Maestro";
                break;
            case "417500": 
                if( len = 16 )
                    type ="Visa Electron";
                break;
            case "560221":
            case "560222":
            case "560223":
            case "560224":
            case "560225":
                if( len == 16 )
                    type = "Australian BankCard";
                break;
        }
        
        //make sure the number is all digits, between 13 and 19 characters
        var cardRegex = /^[0-9]{13,19}$/
        if( !cardRegex.test( num ) )
            type = "unknown";
        
        if( type == "unknown" )
            return type;
        
        // mod10 check
        // sum every  digit starting with the RIGHT-MOST digit
        //         on alternate digits (starting with the NEXT-TO-THE-RIGHT-MOST digit)
        //         sum all digits in the result of TWO TIMES the alternate digit
        //         RATHER than the original digit itself
        var sum = 0;
        var i = len-1;
        
        var multiply = 1;
     
        
        for( i; i >= 0; i--) {
            
            var calc = Number(num.charAt(i)) * multiply;
           
            
            if (calc > 9) {
            	sum += 1;
            	calc = calc - 10;
            }
            
             sum += calc;
             
             if( multiply == 1 )
                multiply = 2;
             else
                multiply = 1;
        }
        
        if( sum % 10 != 0 )
            type = "unknown";
            
        return type;
    }
    }
})();

//zc-widget related JavaScript
zc.widgets = (function() {
    
    return {
        //build an ajax call for a widget
       build_remote_for_widget : function( confirm_q, method, src, before, complete, error, update, success, data )
        {
            var confirmResult = true;
            if( confirm_q != "0" ) //argument exists
                confirmResult = confirm( confirm_q ) //ask the user

            if( confirmResult ) 
            {

                var parameters = {
                   type:    method,
                   url:     src,
                   cache:   false    
                   };

                if( data && data != "0")
                    parameters[ 'data' ] = data;

                if( before != "0" )
                    parameters[ 'beforeSend' ] = before;

                if( complete != "0" )
                     parameters[ 'complete' ] = complete;

                if( error != "0" )
                     parameters[ 'error' ] = error;

                if( update != "0" )
                {
                     parameters[ 'success' ] = function(html) {
                          $("#" + update).html( html );
                     };
                }

                //a success block clobbers the update
                if( success != "0")
                    parameters[ 'success' ] = success;

                $.ajax( parameters );
            }
        },
        //build a form ajax call for remote_form_for
        build_remote_for_widget_form : function ( confirm_q, method, src, before, complete, error, update, success, validate, form  )
        {
            if( !validate || (validate && $(form).valid() ) ) { //make sure we're not submitting an invalid form
                var data = $(form).serialize();
                this.build_remote_for_widget( confirm_q, method, src, before, complete, error, update, success, data )
            }
        },
        set_cc_note : function( cc_input )
        {
            var cc_num = cc_input.value;
            
            var type = zc.cc.verisign_checksum( cc_num );
            var message = "";
            
            if( type == "unknown" )
                message = "There is a problem with your credit card number";
            else
                message = type;
                
            
            $('#' + cc_input.id + '_note').html( message );
        },
        toggle_tip : function( event )
        {   
            
            var show_tip = event.data.show_tip || event.target;
            var tip_id = event.data.tip_id;
            var tip_elt_id = event.data.tip_elt_id;
            
            
            if( $(show_tip).hasClass( "show_tip" ) )
            {
                //hide others
                $(".tip_container").fadeOut( "fast" );
                $(".hide_tip").removeClass( "hide_tip" ).addClass( "show_tip" );   
                
                
                
                $( show_tip ).removeClass( "show_tip" ).addClass( "hide_tip" );
                 
                 //move the tip
                var p = $( show_tip ).position();
                $('#'+tip_id).css( { position: "absolute", left: Math.round(p.left+42)+"px", top: Math.round(p.top) + "px"});
                
                
                //move the arrow
                $(".tip_arrow").css( { position: "absolute", left: Math.round(p.left+42-6)+"px", top: Math.round(p.top+7)+"px"});
                
                //fade in
                $("#"+tip_id+",.tip_arrow").fadeIn( "fast" );
                    
                
                //track events elsewhere
                $("body").bind( "click", {show_tip: show_tip, tip_id: tip_id, tip_elt_id: tip_elt_id}, zc.widgets.toggle_tip );                
                $("#"+tip_id+",.tip_arrow,#"+tip_elt_id).bind( "click.capture", function( event ) { return false; } );

            }
            else {
                
                //flip show button
                $( show_tip ).removeClass( "hide_tip" ).addClass( "show_tip" );         
                
                //unbind events as necessary
                $(".zc_form_element,.tip_arrow,.zc_form_element input").unbind( "click.capture" );     
                $("body").unbind( "click" ); 

                //fade out
                $("#"+tip_id+",.tip_arrow").fadeOut( "fast" );
              
               
            }
           
            //kill the event (do not allow further propogation)
            return false;
        },
        showErrors : function( errorMap, errorList )
        {
            var len = errorList.length;
            var i = 0;
            
          
            for( i; i<len; i++)
            {
                var elt = errorList[i].element;
                var msg = errorList[i].message;
                               
                $("#"+elt.id+"_error_content .error_message").html( msg );
               
               
               $("#"+elt.id+"_error").css( { top: $(elt).position().top-10 });
               
                $("#"+elt.id+"_error").show();
                
            }
            
            len = this.successList.length;
            i = 0;
            
             for( i; i<len; i++)
             {
                    var elt = this.successList[i];

                    $("#"+elt.id+"_error").hide();

             }
            
        }
        
    }
})();



// add the fckeditor to textareas that have the fckeditor class
 $(document).ready( function () {
     $(".fckeditor").each(function(index) {
         this.fck = new FCKeditor(this.id, '600', '400');
         this.fck.BasePath = "/styles/template/fckeditor/";
         this.fck.ToolbarSet = 'Standard';
         this.fck.ReplaceTextarea();
     });
 });
 
 $(document).ready( function () {
      
      
      $(".vr").height( $("#elements").height() );
      
      
      // Check for placeholder attribute support
      // if (!("placeholder" in $('<input>')[0])) {
      //     $(".registration .zc_form_element input[placeholder]").addClass( "placeheld" );
      //           $(".registration .zc_form_element input[placeholder]").placeHeld();
      //       }
      
      //Toy binding for banner expanding
      $("#expand_banner").bind( "click", function() {
          
         $("#compressed_text").hide();
         $("#expanded_text").show();
         $(".bubble_container").hide();
      });

 });
