// AJAX CSRF Protection
$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

// Clears the helper text from input fields onFocus and restores onBlur
function initClear() {
    var clearMePrevious = "";

    // clear input on focus
    $('.clearMe').focus(function() {
    	if($(this).val()==$(this).attr('title')) {
    		clearMePrevious = $(this).val();
    		$(this).val('');
    }
    });

    // if field is empty afterward, add text again
    $('.clearMe').blur(function() {
    	if($(this).val()=='') {
    		$(this).val(clearMePrevious);
    	}
    });
}

// Ajax sign in switch
function sign_in_status() {
    $.ajax({
        type: "POST",
        url: sign_in_status_url,
        beforeSend: function(xhr) {
            //$('.account').html("Loading...");
      },
      success: function(data, textStatus, xhr) {
          if (data == 1) {
              $('.account').html("Log Out");
              $('.account').attr("href", logout_url);
          }
      }});
}

//generic function for tracking a Google event
function trackGAEvent(category, action, label, value) {
	_gaq.push(['_trackEvent', category, action, label, value]);
	//alert(category + ' ' + action + ' event:\n' + label + ' = ' +value);
};

//returns true if the form field is empty. 
function fieldEmpty(selector) {
	return ($(selector).val() == '');
}

//returns true if the form fields do not match. 
function fieldsMatch(selectora, selectorb) {
	return ($(selectora).val() == $(selectorb).val());
}

//returns true if the field contains a valid password
function validPassword (selector) {
        var val = $(selector).val();
        return val.length >= 6;
}

//returns true if the form field contains a valid email
function validEmail (selector) {
	var val = $(selector).val();
	return (val.match(/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i));
}

//returns true if the form field contains a valid phone number
function validPhone (selector) {
	var val = $(selector).val();
	var pn = val.replace(/[^0-9]+/g, '');
	if (pn.charAt(0) == '0') return false;
	if (pn.length < 10) return false;
	if (pn.length == 10 && pn.charAt(0) == '1') return false;
	var num = '';
	if (pn.charAt(0) == '1') {
		num = '1 ';
		pn = pn.substring(1);
	}
	num += '(' + pn.substring(0,3) + ') ';
	pn = pn.substring(3);
	num += pn.substring(0,3) + '-' + pn.substring(3,7);
	pn = pn.substring(7);
	if (pn.length > 0) {
		num += ' x' + pn;
	}
	$(selector).val(num);
	return true;
}

//show/hide password field text
function showpw (cb, id) {
	var t = cb.checked ? 'text' : 'password';
	if (/msie/i.test(navigator.userAgent)) {
		var xtra = id + '_showpw';
		if (!document.getElementById(xtra)) {
			$('#'+id).after('<input type="text" id="'+xtra+'">');
			$('#'+xtra).width($('#'+id).width());
		}
		if (cb.checked) {
			$('#'+xtra).val($('#'+id).val());
		} else {
			$('#'+id).val($('#'+xtra).val());
		}
		$('#'+xtra).toggle(cb.checked);
		$('#'+id).toggle(!cb.checked);
	} else {
		document.getElementById(id).type = t;
	}
}

// survey in modal window
/*$("#survey-widget-link").fancybox({ 
	width: 700,   
	height: 420, 
	hideOnContentClick: false,
	hideOnOverlayClick: false,
	scrolling : 'auto',
	type: 'iframe'  
}); */

// Ajax survey launcher
function survey() {
    if (launch_survey == true) {
        $.ajax({
            type: "GET",
            url: survey_url + "?random=" + Math.floor(Math.random()*100000),
            beforeSend: function(xhr) {
                //$('.account').html("Loading...");
          },
          success: function(data, textStatus, xhr) {
              if (data == 1) {
    			  $('#survey-widget-link').trigger('click');
    			  //alert(data);
    			  //var test = data;
              }
          }});
    }
}

sign_in_status();
survey();

$(document).ready(function() {
	// Sets the Holiday Message cookie to be visible if rendered by Django
	var holidayOff = $.cookie('holidayOff');
	$("#holiday_close").click(function(){
		$(".holidayMsg").slideUp('fast');
		$.cookie('holidayOff', 'collapsed', {expires:7, path: '/'});
	});
	if (holidayOff == 'collapsed') {
		$(".holidayMsg").hide();
	} else {
		$(".holidayMsg").slideDown('slow');
	}
});

//add backgroundColor animation support witnout loading the jQuery UI library
(function(jQuery){
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( !fx.colorInit ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
				fx.colorInit = true;
			}
			var rgba = [
				Math.max(Math.min( parseInt( (fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0),
				Math.max(Math.min( parseInt( (fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0),
				Math.max(Math.min( parseInt( (fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0),
				Math.max(Math.min( parseFloat( (fx.pos * (fx.end[3] - fx.start[3])) + fx.start[3]), 1), 0)
			];
			try {
				fx.elem.style[attr] = "rgba(" + rgba.join(",") + ")";
			} catch (e) { //ie 8 and below
				fx.elem.style[attr] = "rgb(" + [rgba[0],rgba[1],rgba[2]].join(",") + ")";
			}
		}
	});
	function getColor(elem, attr) {
		var color;
		do {
			color = jQuery.curCSS(elem, attr);
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;
			attr = "backgroundColor";
		} while ( elem = elem.parentNode );
		return getRGB(color);
	};
	function getRGB (color) {
		var result;
		if ( color && color.constructor == Array && color.length == 3 )
			return color;
		if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([-+]?[0-9]*\.?[0-9]+)\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), parseFloat(result[4])];
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3]), 1];
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, 1];
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16), 1];
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16), 1];
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, 1];
	}
})(jQuery);

