// console.log('functions.js has been added');

//OBJECTS

var BrowserDetect = { //use like BrowserDetect.browser, BrowserDetect.version, BrowserDetect.OS
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

//FUNCTIONS

function rand (min, max) {
    // Returns a random number
    // version: 1102.614
    // http://phpjs.org/functions/rand
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647; //int ceiling
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function checkBrowser(insert){
	var browser_name = BrowserDetect.browser;//navigator.appName;
	var browser_version = BrowserDetect.version;//navigator.appVersion;
	var platform = BrowserDetect.OS;//navigator.platform
	
	//document.getElementById(insert).innerHTML= "We have detected you are using"+browser_name+" "+browser_version+".";

	if (browser_name=="Explorer"&&browser_version<=7){
		document.getElementById(insert).innerHTML= "We have detected you are using an out of date browser (Internet Explorer "+browser_version+"). You may experience errors in the site. Please update your browser if errors occur.";

	}else{
		document.getElementById(insert).style.display = 'none';
	}
	
	//alert("You are using "+browser_name+" (version "+browser_version+") on "+platform+"funciton inser is: "+result);
}

$.extend($.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){return false;});
            }else{//Opera, etc.
                $(this).mousedown(function(){return false;});
            }
        });
    });

function checkEmail(email){

var regexp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	return regexp.test(email);

}

function date(format, timestamp) {
	// alert('date ran');
    var that = this,
        jsdate, f, formatChr = /\\?([a-z])/gi,
        formatChrCb, _pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array((++c) - n.length).join("0") + n
            } else {
                return n
            }
        },
        txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
        txt_ordin = {
            1: "st",
            2: "nd",
            3: "rd",
            21: "st",
            22: "nd",
            23: "rd",
            31: "st"
        };
    formatChrCb = function (t, s) {
        return f[t] ? f[t]() : s
    };
    f = {
        d: function () {
            return _pad(f.j(), 2)
        },
        D: function () {
            return f.l().slice(0, 3)
        },
        j: function () {
            return jsdate.getDate()
        },
        l: function () {
            return txt_words[f.w()] + 'day'
        },
        N: function () {
            return f.w() || 7
        },
        S: function () {
            return txt_ordin[f.j()] || 'th'
        },
        w: function () {
            return jsdate.getDay()
        },
        z: function () {
            var a = new Date(f.Y(), f.n() - 1, f.j()),
                b = new Date(f.Y(), 0, 1);
            return Math.round((a - b) / 864e5) + 1
        },
        W: function () {
            var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
                b = new Date(a.getFullYear(), 0, 4);
            return 1 + Math.round((a - b) / 864e5 / 7)
        },
        F: function () {
            return txt_words[6 + f.n()]
        },
        m: function () {
            return _pad(f.n(), 2)
        },
        M: function () {
            return f.F().slice(0, 3)
        },
        n: function () {
            return jsdate.getMonth() + 1
        },
        t: function () {
            return (new Date(f.Y(), f.n(), 0)).getDate()
        },
        L: function () {
            return new Date(f.Y(), 1, 29).getMonth() === 1 | 0
        },
        o: function () {
            var n = f.n(),
                W = f.W(),
                Y = f.Y();
            return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9)
        },
        Y: function () {
            return jsdate.getFullYear()
        },
        y: function () {
            return (f.Y() + "").slice(-2)
        },
        a: function () {
            return jsdate.getHours() > 11 ? "pm" : "am"
        },
        A: function () {
            return f.a().toUpperCase()
        },
        B: function () {
            var H = jsdate.getUTCHours() * 36e2,
                i = jsdate.getUTCMinutes() * 60,
                s = jsdate.getUTCSeconds();
            return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3)
        },
        g: function () {
            return f.G() % 12 || 12
        },
        G: function () {
            return jsdate.getHours()
        },
        h: function () {
            return _pad(f.g(), 2)
        },
        H: function () {
            return _pad(f.G(), 2)
        },
        i: function () {
            return _pad(jsdate.getMinutes(), 2)
        },
        s: function () {
            return _pad(jsdate.getSeconds(), 2)
        },
        u: function () {
            return _pad(jsdate.getMilliseconds() * 1000, 6)
        },
        e: function () {
            throw 'Not supported (see source code of date() for timezone on how to add support)'
        },
        I: function () {
            var a = new Date(f.Y(), 0),
                c = Date.UTC(f.Y(), 0),
                b = new Date(f.Y(), 6),
                d = Date.UTC(f.Y(), 6);
            return 0 + ((a - c) !== (b - d))
        },
        O: function () {
            var a = jsdate.getTimezoneOffset();
            return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4)
        },
        P: function () {
            var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2))
        },
        T: function () {
            return 'UTC'
        },
        Z: function () {
            return -jsdate.getTimezoneOffset() * 60
        },
        c: function () {
            return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb)
        },
        r: function () {
            return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb)
        },
        U: function () {
            return jsdate.getTime() / 1000 | 0
        }
    };
    this.date = function (format, timestamp) {
        that = this;
        jsdate = ((typeof timestamp === 'undefined') ? new Date() : (timestamp instanceof Date) ? new Date(timestamp) : new Date(timestamp * 1000));
        return format.replace(formatChr, formatChrCb)
    };
    return this.date(format, timestamp)
}

// Simulates PHP's date function
/* Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}}; */

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function (runUcwords) {
        return runUcwords.toUpperCase();
    });
}

function refinePermissionModule(){

	$('.user_role_module ul').slideUp();

	$('.user_role_module').click(function(){
/* 		console.log('user module clicked'); */
		$('.user_role_module ul').slideToggle();
	});
	
	var currentPermissions = new Object();

	$('.user_role_module li').each(function(index, roleItem){
		if ($(roleItem).css('font-weight')=='bold'||$(roleItem).hasClass('active')){
			currentPermissions[$(roleItem).find('span:eq(1)').text()] = 'active';
		}else{
			currentPermissions[$(roleItem).find('span:eq(1)').text()] = 'disabled';
		}
	});

	$('.active_permissions li').hover(
		function(){
			$(this).addClass('active').removeClass('disabled');
			$(this).siblings().removeClass('active').addClass('disabled')
		},function(){
			$(this).removeClass('active');
			$(this).siblings().removeClass('disabled');
		}
	);

	$('.active_permissions').mouseleave(function(){ //when not hovering the box it resets to what permissions the page is using
			// console.log(currentPermissions);
		$.each(currentPermissions, function(index, rolePermission){
			$('.active_permissions li:contains('+index+')').addClass(rolePermission);
		});
	});

	$('.active_permissions li').click(function(){

		var permissionObject = new Object();

		$('.user_role_module li').each(function(index, roleItem){
			if ($(roleItem).css('font-weight')=='bold'||$(roleItem).hasClass('active')){
				permissionObject[$(roleItem).find('span:eq(1)').text()] = 'active';
			}else{
				permissionObject[$(roleItem).find('span:eq(1)').text()] = 'disabled';
			}
		});

		$.ajax({
		   type: "POST",
		   url: "/sales/global/refine_permissions.php",
		   data: {saveData:  permissionObject},
		   success: function(msg){
			// console.log(msg);
				if (msg=='true'){
					$('.user_role_module').append('<em>Refreshing page...</em>');
					location.reload();
				}else{
					alert('An error occurred, your changes may not have been saved ('+msg+')');
				}
			}
		 });
	});

} //end function

function updateTooltips(){

	$('[data-tooltip]').unbind().each(function(index, element){ //info icons
			$(element).hover(
				function(){
					$(element).append('<div class="tooltip_placeholder"><div class="tooltip_boundary"><div class="tooltip_border" style="display: none;"><span class="tooltip">'+$(element).attr('data-tooltip')+'</span></div></div></div>').find('.tooltip_border').slideDown('fast');
				},
				function(){
					$(element).find('.tooltip_border').delay(500).slideUp('slow', function(){
						$(element).find('.tooltip_placeholder').remove();
					});
				}
			);
	});
}

function displayTooltip(element, message, duration){
	
	var offset = element.offset();
	
	element.append('<div class="tooltip_placeholder"><div class="tooltip_boundary"><div class="tooltip_border" style="display: none;"><span class="tooltip">'+message+'</span></div></div></div>').find('.tooltip_border').slideDown('fast');
	
	$(element).find('.tooltip_border').delay(duration).slideUp('slow', function(){
		$(element).find('.tooltip_placeholder').remove();
	});
}

	function bugFormValidates(){
		$('.validation_notice').remove();
		var valSum = 0;
		if ($('.bug_form input[name="title"]').val()==''){
			$('.bug_form input[name="title"]').prev('h3').after('<span class="validation_notice">Title must not be blank</span>');
			valSum++;
		}
		if ($('.bug_form input[name="type"]:checked').length<1){
			$('.bug_form input[name="type"]').parents('ul').prev('h3').after('<span class="validation_notice">You must choose a type</span>');
			valSum++;
		}
		if ($('.bug_form textarea[name="details"]').val()==''){
			$('.bug_form textarea[name="details"]').prev('h3').after('<span class="validation_notice">Details must not be blank</span>');
			valSum++;
		}
		if ($('.bug_form input[name="importance"]:checked').length<1){
			$('.bug_form input[name="importance"]').parents('ul').prev('h3').after('<span class="validation_notice">You must state an importance</span>');
			valSum++;
		}
		
		if (valSum === 0){
			return true;
		}else{
			return false;
		}
	}


$(document).ready(function(){
	/*
	if (typeof console == "undefined"){ //browser doesnt have a console
		var console = { log: function() {} }; //make console.log a defined function that does nothing
	}else if (typeof console.log == "undefined"){ //if browser has a console, but no log function
		console.log = function() {}; //define log function
	}*/
	
	// console.log('functions.js is running fine');
	
	updateTooltips();
	
	$('.bug_form').hide();
	$('.bug_icon').add(".bug_trigger").click(function(){
		
		$( ".bug_form" ).dialog({
			autoOpen: true,
					height: 480,
					width: 410,
					zIndex: 100,
					modal: true,
					buttons: {
						"Send Report": function() {
							
							if (bugFormValidates()){
								
								var bugObject = {};
								
								bugObject.title = $('.bug_form input[name="title"]').val();
								bugObject.type = $('.bug_form input[name="type"]:checked').val();
								bugObject.details = $('.bug_form textarea[name="details"]').val();
								bugObject.importance = $('.bug_form input[name="importance"]:checked').val();
								bugObject.addInfo = $('.bug_form textarea[name="additional_info"]').val();
								bugObject.userAgent = BrowserDetect.browser+' '+BrowserDetect.version+' ('+BrowserDetect.OS+')';
								bugObject.page = location.href;
								bugObject.php_errors = [];
								
								$('.bug_form input.php_error').each(function(index, element){
									bugObject.php_errors.push($(element).val());
								});
								
/* 								console.log(bugObject); */
								
								$(".bug_form").dialog("close");
								$.ajax({
								   type: "POST",
								   url: "/sales/bugtracker/submit_bug.php",
								   data: bugObject,
								   success: function(msg){
										if (msg !="true"){
											alert("Error: Bug not submitted.");
											console.log(msg);
										}else{
											alert("Thanks for submitting your bug report. We will be on it asap");
										}

									}
								});
							}
							
						},
						Cancel: function() {
							$(this).dialog( "close" );
						}
					},
					close: function() {
						// console.log('dialog closed');
					}
				});
		});
		
		$('.php_error_icon').click(function(){
			
			$(".php_errors").dialog({
				autoOpen: true,
				zIndex: 100,
				width: 1024,
				title: 'PHP Errors',
				modal: true
			});
			
		});
		
		if ($('.php_errors .errors ul li').size()==0){
			$('.php_error_icon').removeClass('php_error_icon').addClass('php_valid_icon').attr('data-tooltip', 'No errors in PHP');
		}else{
			$('.php_error_icon').before('<span class="php_error_count">'+$('.php_errors .errors ul li').size()+'</span>');
		}
	
	
	
  		$(".validateForm").validate({
			rules: {
				moleculeSelect: "greaterThanZero"
			}
		});
		$('label.labelover').labelOver('over-apply');
		$("#popup").hide();
		$("a.toggle_popup").live("click",function(){
			$("#popup").toggle();
		});
		$(".people li").hide();
		$(".people li:first-child").show();
		$(".rdonly").hide();
	

	
	
    $('.delete').click(function() {
        var answer = confirm("Delete this item?")
        if (answer){
            return true;
        }
        else{
            return false;
        };
    });

	$('.override').click(function() {
        if (confirm("Override the payment? Please note that if you do this the client will be emailed their confirmation emails, including their receipt")){
            return true;
        }
        else{
            return false;
        };
    });

	$('.existing_licensees').click(function() {	
		confirm("Coming soon")
	});


	$("form[name=labelgen] select").change(function() {
		if($(this).attr('value')==""){
			$("form[name=labelgen] input[name=catnumInput]").attr('value', '');
			$("form[name=labelgen] .manual").show();
			$("form[name=labelgen] input[name=catnumInput]").attr('readonly', '');
		} else {
			$("form[name=labelgen] input[name=catnumInput]").attr('value', $("form[name=labelgen] select option:selected").attr('id'));
			$("form[name=labelgen] input[name=catnumInput]").attr('readonly', 'readonly');
			$("form[name=labelgen] .manual").hide();
		}
	});
});

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-11378169-3']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();



	
