var thisPointer;
var socialIconOrigin;
var canvasFunctions = {
    canvasInterval: 0,
    //Delete canvasReady2 once all canvases are converted over to the new function
    canvasReady2: function(thisCanvas, fnCallback){
        // Checks if the explorercanvas has converted Canvas to VML
        // When ready it is sent to be rendered.
        if(thisCanvas.getContext){
            if ($.isFunction(fnCallback)) {
                fnCallback.call(this, thisCanvas);
            }
        }else{
            var canvasTimer = setTimeout(function(){
            	canvasFunctions.canvasReady2(thisCanvas, fnCallback)
        	}, 500);
        }
    },
    canvasReady: function(thisCanvas, fnCallback){
        // Checks if the explorercanvas has converted Canvas to VML
        // When ready it is sent to be rendered.
        if(thisCanvas.getContext){
            if ($.isFunction(fnCallback)) {
                fnCallback.call(this, thisCanvas);
            }
        }else{
            var canvasTimer = setTimeout(function(){
            	canvasFunctions.canvasReady2(thisCanvas, fnCallback)
        	}, 500);
        }
    },
    // canvasReady: function(thisCanvas){
        // // Checks if the explorercanvas has converted Canvas to VML
        // // When ready it is sent to be rendered.
        // if(thisCanvas.getContext){
            // canvasFunctions.drawSwoosh(thisCanvas);
        // }else{
            // var canvasTimer = setTimeout(function(){
            	// canvasFunctions.canvasReady(thisCanvas)
        	// }, 500);
        // }
    // },
    drawSwoosh: function(thisCanvas)
    {
        var ctx = thisCanvas.getContext('2d');
        var documentWidth;

        // Ensure that DocumentWidth doesn't drop below 960px
        if ($(document).width() > 960)
        {
            documentWidth = $(document).width();
        }
        else
        {
            documentWidth = 960;
        }
        var multiplier = documentWidth / 500;
        $('#swoosh_canvas').attr('width', documentWidth);

        // Set swoosh gradient colors
        var swooshGrad = ctx.createLinearGradient(0, 0, 500 * multiplier, 0);
        swooshGrad.addColorStop(0, '#a41a11');
        swooshGrad.addColorStop(0.5, '#f52018');

        // Draw the swoosh
        ctx.beginPath();
        ctx.moveTo(0, 29);
        ctx.bezierCurveTo(0 * multiplier, 29, 42 * multiplier, 0, 109 * multiplier, 0);
        ctx.bezierCurveTo(177 * multiplier, 0, 197 * multiplier, 6, 263 * multiplier, 25);
        ctx.bezierCurveTo(330 * multiplier, 45, 362 * multiplier, 55, 413 * multiplier, 55);
        ctx.bezierCurveTo(475 * multiplier, 55, 500 * multiplier, 20, 500 * multiplier, 20);
        ctx.lineTo(500 * multiplier, 120);
        ctx.lineTo(0 * multiplier, 120);
        ctx.closePath();
        ctx.fillStyle = swooshGrad;
        ctx.fill();
    }
};

var generalFunctions =
{
	videoEmbed: function(videoId, videoWidth, videoHeight){
		//Generic video embedding	    	   
    	var videoWidth = (typeof videoWidth != 'undefined') ? videoWidth : 600;
    	var videoHeight = (typeof videoHeight != 'undefined') ? videoHeight : 400;
        swfobject.embedSWF("http://www.youtube.com/e/" + videoId + "?enablejsapi=1&playerapiid=product_video", videoId, videoWidth, videoHeight, "8", null, null, generalFunctions.videoParams, generalFunctions.videoAtts);
 	},
 	videoPopup: function(videoId) {
 		var contents = $('<div class="video_youtube" id="' + videoId + '" />').css({
 			width: 600,
 			height: 400
 		});
 		generalFunctions.displayNotice(contents);
 		generalFunctions.videoEmbed(videoId, 600, 400);
 	},
    videoParams: {
        allowScriptAccess: "always",
        wmode: "transparent"
    },
    videoAtts: {
    },
    //Translate field names from Stars database to Salesforce names
    dbToSalesforce: function(dbField){
		switch(dbField){
			case 'address':
			return 'MailingStreet';
			break;
			case 'city':
			return 'MailingCity';
			break;
			case 'company':
			return 'AccountName';
			break;
			case 'country_id':
			return 'MailingCountry';
			break;
			case 'email':
			return 'Email';
			break;
			case 'fax':
			return 'Fax';
			break;
			case 'first_name':
			return 'FirstName';
			break;
			case 'last_name':
			return 'LastName';
			break;
			case 'market_id':
			return 'MarketID';
			break;
			case 'mobile_phone':
			return 'MobilePhone';
			break;
			case 'phone':
			return 'Phone';
			break;
			case 'postalcode':
			return 'MailingPostalCode';
			break;
			case 'state_id':
			return 'MailingState';
			break;
			case 'title':
			return 'Title';
			break;
		}
	},
    displayDropdown: function(wrapperId, parentObject, data){
    	var dropdownWrapper = $('<div id="'+ wrapperId + '" class="dropdown_wrapper">');
    	var dropdownValue = $('<div class="dropdown_head">').html('Did you mean?..');
			dropdownWrapper.append(dropdownValue);
    	$(data).each(function(){
			var dropdownValue = $('<div class="dropdown_row" id="' + this.Id + '">').html(this.Name + (this.BillingCity != null ? ('<span>' + this.BillingCity + ', ' + this.BillingState + '</span>') : ('<span>' + this.ShippingCity + ', ' + this.ShippingState + '</span>')) + '</span>');
			dropdownWrapper.append(dropdownValue);
		});
		$(parentObject).after(dropdownWrapper);
    },
    displayNotice: function (message, width, padding, height, title, disallowClose) {
        
        if(width){
        	$('#alert').css('width', width + 'px');
        } else {
        	$('#alert').css('width','');
        }
        
        try {
        	$('#alert').css('max-height', (height ? height + 'px': 'auto'));
        } catch(err) {
        	//IE Sucks!
        }
        $('#alert').css('padding', (padding ? padding + 'px': '10px'));
		
		$('#alert_title').html(title ? title: '');
        
        if(disallowClose == '1') {
            $('#alert_close').hide();
        }
        else {
            $('#alert_close').show();
        }
        $('#alert').html(message);
        $('#alert_overlay').css('width', $(document).width() + 'px').css('height', $(document).height() + 'px').show();
        $('#alert_wrapper').css('top', $(window).scrollTop() + ($(window).height() * 0.2) + 'px').css('left', ($(window).width() - $('#alert').width()) / 2 + 'px');
    	
    },
    hideDropdown: function() {
    	$('.dropdown_wrapper').remove();
    },
    hideNotice: function () {
    	$('#alert').find('.editor').each(function(){
			tinyMCE.execCommand('mceRemoveControl', false, $(this).attr('id'));
		});
		$('#alert_overlay').hide();
    },
    resultsList: function(theseResults, keyMatch, maxHeight, additionalData, fnCallback) {
	// theseResults is expecting an object.  This function allows a results window to display information important to a user, while keeping information for the database behind the scenes but still accessible.
	// keyMatch is expecting an array of objects defining the columns (in the order it should be displayed)
	// required fields are key and name. width is optional.
	// example: [{ key: "firstName", name: "First Name", width: 300 },{ key: "lastName", name: "Last Name", width: 400}]
	// additionalData is HTML to display after the list.  This is used on the contact map for adding new accounts.
	// fnCallback is the function to call when one of the results is selected.
		var results = $('<div class="results">');
		 
		var resultsSubhead = $('<div class="results_subhead">');
		$(keyMatch).each(function(){
			resultsSubhead.append($('<div class="results_column">').css('width', this.width?this.width:'auto').html(this.name?this.name:''));
		});
		results.append(resultsSubhead);
		
		var resultsList = $('<div class="results_list">').css({
			maxHeight: maxHeight?maxHeight:'auto'
		});
		
		if(theseResults && theseResults.length > 0){
			$(theseResults).each(function(){
				var thisResult = this;
				var thisResultRow = $('<div class="result results_row">');
				$(keyMatch).each(function(){
					var thisKeyMatch = this;
					var thisCol = $('<div class="results_column">').css({
						width: this.width?this.width:'auto',
						whiteSpace: 'pre-wrap'
					});
					//Eval is evil. But otherwise I don't know how to handle a key that includes a child object - example: "Entered_By__r.Name"
					var thisColContent = $('<div class="results_column_content">').html(eval('thisResult.' + this.key)?eval('thisResult.' + this.key):'');
					thisCol.append(thisColContent);
					//Make something editable
					if(this.editable == true) {
						thisCol.prepend($('<div class="editable" title="Make Changes">')).on('click', function(e){
							var editForm = $('<form>');
							editForm.append('<h3>Edit ' + thisKeyMatch.name + '</h3>');
							switch(thisKeyMatch.type){
								case 'textarea':
									editForm.append($('<textarea class="grid_6" rows="12" name="' + thisKeyMatch.key + '">').val(eval('thisResult.' + thisKeyMatch.key)));
									editForm.append($('<div class="clear_both">'));
									editForm.append($('<input type="submit" class="input_button" value="Submit" />'));
								break;
								case 'date':
									editForm.append($('<input type="text" class="grid_3 input_date_range" name="' + thisKeyMatch.key + '">').val(eval('thisResult.' + thisKeyMatch.key)).datepicker({
								        dateFormat: 'yy-mm-dd'
								    }));
									editForm.append($('<div class="clear_both">'));
									editForm.append($('<input type="submit" class="input_button" value="Submit" />'));
								break;
							}
							editForm.on('submit', function(e){
								e.preventDefault();
								var updateField = $(this).serializeJSON();
								sfFunctions.sfUpdate(thisResult.attributes.type, thisResult.Id, JSON.stringify(updateField));
								generalFunctions.hideNotice();
								thisColContent.html(updateField[thisKeyMatch.key]);
							});
							generalFunctions.displayNotice(editForm);
						});
					}
					thisResultRow.append(thisCol);
				});
				resultsList.append(thisResultRow);

				// if a callback function is defined, use it when a result is clicked.
				if($.isFunction(fnCallback)){
					$(thisResultRow).on('click', function(e){
						e.preventDefault();
						fnCallback.call(this, thisResult);
					});
				}
			});
		} else {
			var thisResultRow = $('<div class="result results_row">').html('No results were found.');
			resultsList.append(thisResultRow);
		}
	
		results.append(resultsList);
		
		if(additionalData){
			var resultsAdditional = $('<div class="results_additional">').append($('<div class="results_row">').html(additionalData));
			results.append(resultsAdditional);
		}
		if(theseResults){
			var resultsCount = $('<div class="results_count">').html('<span>' + theseResults.length + '</span> Results Shown');
			results.append(resultsCount);
		}
				
		return results;
	},
    trackEvent: function(category, action, label) {
    	if(typeof _gaq != 'undefined'){
        	_gaq.push(['_trackEvent', category, action, label]);
    	}
    },
    validateField: function(thisInput) {
        var returnValue = true;
        var vForm = $(thisInput).parents('form');
        switch ($(thisInput).attr('name')) {
        case 'FirstName':
        case 'LastName':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter a First Name'));
                if(typeof _gaq != 'undefined'){
                	_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
            	}
                returnValue = false;
            }
            break;
        case 'ActivityDate':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please select a Date'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
    			}
    			returnValue = false;
            }

            break;
        case 'Email':
            // Checks for an email address of anything@anything.anything
            if (!$(thisInput).val().match(/.+@.+\..+/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter a valid Email Address'));
                if(typeof _gaq != 'undefined'){
	                _gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'AccountName':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter a Company'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'MailingStreet':
        case 'BillingStreet':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/m)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter an Address'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'MailingCity':
        case 'BillingCity':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter a City'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'MailingState':
        case 'BillingState':
            // Checks for a state value
            if ($(thisInput).val() === '0') {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please select a State'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(this).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'MailingPostalCode':
        case 'BillingPostalCode':
            // Checks for at least one non-space character
            if (!$(thisInput).val().match(/^.+[\S].+$/)) {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please enter a Postal Code'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        case 'MailingCountry':
        case 'BillingCountry':
            // Checks for a Country value
            if ($(thisInput).val() === '0') {
                $(thisInput).addClass('form_not_valid');
                $(thisInput).after($('<div class="input_error">').html('Please select a Country'));
                if(typeof _gaq != 'undefined'){
					_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'alert_' + $(thisInput).attr('name')]);
                }
                returnValue = false;
            }
            break;
        }
        return returnValue;
    },
    validateForm: function (vForm) {
	    if(typeof _gaq != 'undefined'){
			_gaq.push(['_trackEvent', 'Forms', $(vForm).attr('id'), 'submit']);
		}
		$('.input_error').remove();
        var isValid = true;
        $(vForm).find('.required').each(function() {
            if (!generalFunctions.validateField(this)) {
                isValid = false;
            }
        });
        return isValid;
    }
};

var mapFunctions = {
    infowindowArray: [],
    map: null,
    mapMarkerArray: [],
    mapGeocoder: null,
    mapOptions: {
        zoom: 3,
        center: null,
        mapTypeId: null
    },
    clearInfowindows: function() {
        $(mapFunctions.infowindowArray).each(function() {
            this.close();
        });
    },
    clearMarkers: function() {
		$(mapFunctions.mapMarkerArray).each(function() {
            this.setMap(null);
        });
        mapFunctions.mapMarkerArray = [];
    },
    geocode: function(geocodeAddress, fnCallback) {
		var mapGeocoder = new google.maps.Geocoder();
    	geocodeAddress = geocodeAddress.replace(/null/gi, '').replace(/\\n/gi, ' ').replace(/\\r/gi, ' ');
        mapGeocoder.geocode({
            'address': geocodeAddress
        }, function(results, status) {
            if (results) {
            	var thisLatLng;
            	if ($.isArray(results)) {
            		if(results[0]){
	            		thisLatLng = results[0].geometry.location;
            		}
            	} else {
            		thisLatLng = results.geometry.location;
            	}
            	if ($.isFunction(fnCallback)) {
		            fnCallback.call(this, thisLatLng ? thisLatLng.lat() : null, thisLatLng ? thisLatLng.lng() : null);
		        } else {
		        	return false;
		        }
			} 
        });

    },
    placeMarker: function(thisMap, lat, lng, infoContent, markerType, fnCallback) {
        var markerPosition;
        switch (markerType) {
        	case 'red':
        	markerPosition = new google.maps.Point(0,0);
        	break;
        	
        	case 'orange':
        	markerPosition = new google.maps.Point(0,10);
        	break;
        	
        	case 'yellow':
        	markerPosition = new google.maps.Point(10,0);
        	break;
        	
        	case 'green':
        	markerPosition = new google.maps.Point(10,10);
        	break;
        	
        	case 'blue':
        	markerPosition = new google.maps.Point(20,0);
        	break;
        	
        	case 'purple':
        	markerPosition = new google.maps.Point(20,10);
        	break;
        	
        	default:
        	markerPosition = new google.maps.Point(0,0);
        	break;
        }
        var markerIcon = new google.maps.MarkerImage("https://vault.trilithic.com/template/marker_sprites.png",
        	//Marker display dimensions (size)
        	new google.maps.Size(10,10),
        	//Marker default sprite position (origin)
        	markerPosition,
        	//Marker anchor
        	new google.maps.Point(5,5)
        );
        //markerIcon.origin(new google.maps.Point(0,44));
        var thisMarker = new google.maps.Marker({
            icon: markerIcon,
            map: mapFunctions.map,
            position: new google.maps.LatLng(lat, lng)
        });
        mapFunctions.mapMarkerArray.push(thisMarker);
        if(infoContent){
	        google.maps.event.addListener(thisMarker, 'click', function() {
	            mapFunctions.clearInfowindows();
	            var infowindow = new google.maps.InfoWindow({
	                content: infoContent
	            });
	            infowindow.open(mapFunctions.map, thisMarker);
	            mapFunctions.infowindowArray.push(infowindow);
	        });
        }
        if ($.isFunction(fnCallback)) {
            fnCallback.call(this, thisMarker);
        }
    }
};

var sfFunctions = { 
    sfDelete: function(jObject, jSalesforceId, fnCallback){
    	$.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_delete',
            jObject: jObject,
            jSalesforceId: jSalesforceId
        }, function(data) {
            if ($.isFunction(fnCallback)) {
                fnCallback.call(this, data);
            }
        });
    },
    sfDescribe: function(jObject, fnCallback){
    	$.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_describe',
            jObject: jObject
        }, function(data) {
            if ($.isFunction(fnCallback)) {
                fnCallback.call(this, data);
            }
        });
    },
    sfInsert: function(jObject, jContent, fnCallback) {
        $.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_insert',
            jObject: jObject,
            jContent: jContent
        }, function(data) {
            if($.isFunction(fnCallback)) {
                fnCallback.call(this, data);
            }
        });
    },
    sfMore: function(jURL, fnCallback) {
    	var thisData = {};
        $.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_more',
            jURL: jURL
        }, function(data) {
        	//If thisData already has data, append the new results
        	if(thisData.records){
        		$(data.records).each(function(){
        			thisData.records.push(this);
        		});
        	} else {
        		thisData = data;
        	}
	        if(data.nextRecordsUrl){
        		sfFunctions.sfMore(data.nextRecordsUrl, fnCallback);
        	} else {
        		if($.isFunction(fnCallback)) {
	                fnCallback.call(this, thisData);
	            }
            }
		});
    },
    sfQuery: function(jQueryType, jQueryString, fnCallback) {
        $.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_query',
            jQueryType: jQueryType,
            jQuery: jQueryString
        }, function(data) {
        	
        	if(data.nextRecordsUrl){
        		sfFunctions.sfMore(data.nextRecordsUrl, function(moreData){
        			$(moreData.records).each(function(){
        				data.records.push(this);
        			});
        			if($.isFunction(fnCallback)) {
		                fnCallback.call(this, data);
		            }
        		});
        	} else {
        		if($.isFunction(fnCallback)) {
	                fnCallback.call(this, data);
	            }
            }
        });
    },
    sfUpdate: function(jObject, jSalesforceId, jContent, fnCallback) {
        $.getJSON('/_inc/_ajx/ajxSfActions.php', {
            action: 'sf_update',
            jObject: jObject,
            jSalesforceId: jSalesforceId,
            jContent: jContent
        }, function(data) {
            if($.isFunction(fnCallback)) {
                fnCallback.call(this, data);
            }
        });
    }
};

// Timer capable of pause and resume
function Timer(callback, delay) {
    var timerId, start, remaining = delay;
    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };
    this.resume = function() {
        start = new Date();
        timerId = window.setTimeout(callback, remaining);
    };
    this.resume();
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

$(document).ready(function() {
	
	//Serialize forms to JSON
	$.fn.serializeJSON = function() {
		var json = {};
			$.map($(this).serializeArray(), function(n, i){
				json[n['name']] = n['value'];
			});
		return json;
	};


	// Footer Swoosh Stuff
    var thisCanvas = document.getElementById('swoosh_canvas');
    if(thisCanvas){
	    canvasFunctions.canvasReady2(thisCanvas, function(){
	    	canvasFunctions.drawSwoosh(thisCanvas);
	    });
	    
	    // Redraw Swoosh on Resize
	    $(window).resize(function() {
	        canvasFunctions.drawSwoosh(thisCanvas);
	    });
    }
	
	// Video player
	if($('.video_player').length){
		$('.video_player').each(function(){
			var videoVars = {
				file: "https://vault.trilithic.com/instruments/webcasts/" + $(this).attr('id')
			};
			swfobject.embedSWF("https://vault.trilithic.com/template/player.swf", $(this).attr('id'), "620", "372", "9.0.0","/Library/swfobject/expressInstall.swf", videoVars, generalFunctions.videoParams, generalFunctions.videoAtts);
		});
	}
	
	//YouTube Player
	if($('.video_youtube').length){
		$('.video_youtube').each(function(){
			if($(this).attr('id') && $(this).attr('id')!=''){
				generalFunctions.videoEmbed($(this).attr('id'), $(this).attr('width'), $(this).attr('height'));
			}
		});
	}
	
	//Initialize Product Videos
    $('#product_video').each(function(){
        if ($(this).attr('name') && $(this).attr('name') != '') {
        	var thisVid = $(this).attr('name');
            swfobject.embedSWF("http://www.youtube.com/e/" + thisVid + "?enablejsapi=1&playerapiid=product_video", "product_video", "300", "251", "8", null, null, generalFunctions.videoParams, generalFunctions.videoAtts);
        } else if ($(this).attr('title') && $(this).attr('title') != '') {
        	var thisVid = $(this).attr('title');
            swfobject.embedSWF("http://www.youtube.com/e/" + thisVid + "?enablejsapi=1&playerapiid=product_video", "product_video", "300", "251", "8", null, null, generalFunctions.videoParams, generalFunctions.videoAtts);
        }
    });
        
    // Load Google Map
    if($('#map_canvas').length){
    	var mapOptions = {
    		zoom: 3,
    		center: new google.maps.LatLng(40.013, -85.9826),
        	mapTypeId: google.maps.MapTypeId.TERRAIN
    	}
    	mapFunctions.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    	if(typeof vLocationLat != 'undefined' && typeof vLocationLong != 'undefined'){
	    	if(vLocationLat != 0 && vLocationLong != 0){
				mapFunctions.placeMarker(mapFunctions.map, vLocationLat, vLocationLong, vLocationContent?vLocationContent:null);
			}
    	}
	}
    
    //Enable TinyMCE
    $('.editor').filter(":visible").each(function(){
    	tinyMCE.execCommand('mceAddControl', false, $(this).attr('id'));
    });
    
    // Use JQuery UI to activate date pickers.
    $('.input_date_range').datepicker({
        dateFormat: 'yy-mm-dd'
    });
    
    //Clear default input text on click
    $('.input_clear').live('focus', function(e) {
    	$(this).val('');
    	$(this).removeClass('input_clear');
    });
    
    //Image Magnifier
    $('a.img_magnify').live('click', function(e) {
        e.preventDefault();
        generalFunctions.displayNotice("<img src='" + $(this).attr('href') + "' />", null, 10);
    });
        
    //Close alert
    $('#alert_close').click(function() {
        generalFunctions.hideNotice();
    });
    
    //Close alert on escape
    $(document).keyup(function(e) {
        if (e.keyCode === 27) {
            generalFunctions.hideNotice();
        }
    });
    
    //Alert Draggable
    $('#alert_wrapper').draggable({
        handle: '#alert_header'
    });
    
    // Results Hover - Used for Quickadd, Contacts, and Options
    $('.results_row').live('mouseover mouseout', function(event) {
    	event.stopPropagation();
        switch (event.type) {
        	case 'mouseover':
            $(this).addClass('results_row_hover');
            break;
        	case 'mouseout':
            $(this).removeClass('results_row_hover');
            break;
        }
    });
    
    //Results close
    $('.results_close').click(function() {
        $(this).parents('.results_wrapper').hide('blind', 250);
    });    
    
    // Button Hovers
    $('.input_button').live('mouseover mouseout', function(e) {
        switch(e.type){
        	case 'mouseover':
            $(this).addClass('input_button_hover');
        	break;
        	
        	case 'mouseout':
            $(this).removeClass('input_button_hover');
            break;
        }
    });

    $('.input_button_secondary').live('mouseover mouseout', function(event) {
        if (event.type === 'mouseover') {
            $(this).addClass('input_button_secondary_hover');
        }
        else if (event.type === 'mouseout') {
            $(this).removeClass('input_button_secondary_hover');
        }
    });
    
    //Social button hovers
    $('.social_icon').hover(function(e) {
    	if($(this).css('backgroundPosition')) {
	    	var socialIconOrigin = $(this).css('backgroundPosition').split(' ');
	        $(this).css('backgroundPosition', '-10px ' + socialIconOrigin[1]);
        }
    }, function (e) {
    	if($(this).css('backgroundPosition')) {
			$(this).css('backgroundPosition', socialIconOrigin[0] + ' ' + socialIconOrigin[1])
		}
    });
    
    // Accordion Stuff
    $('.accordion_header:first').addClass('accordion_header_active');

    $('.accordion_header:gt(0)').next('ul').hide();

    $('.accordion_header').click(function ()
    {
        if (!$(this).hasClass('accordion_header_active'))
        {
            $('.accordion_header_active').removeClass('accordion_header_active').next('ul').hide('blind', 250);
            $(this).addClass('accordion_header_active').next('ul').show('blind', 250);
        }
    });
	// Contact Form - Toggle state select based on country
    $('select[name="MailingCountry"], select[name="BillingCountry"], select[name="ShippingCountry"]').live('change', function() {
    	var thisForm = $(this).parents('form');
        $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
            action: 'contact_geography',
            jCountryCode: $(this).val()
        }, function(data) {
            if (data.states.length) {
                $('.input_state_international').attr('disabled', 'disabled').hide();
                contactEditState = thisForm.find('.input_state_domestic');
                currentState = contactEditState.val();
                contactEditState.addClass('required').removeAttr('disabled').show().parents('.input_required_wrapper').show();
                contactEditState.empty().append($('<option value="0">').html('Select a State'));
                $(data.states).each(function() {
                    contactEditState.append($('<option value="' + this.state_short + '">').html(this.state_name));
                });
                contactEditState.val(currentState == 0 ? $('.input_state_international').val() : currentState);
            } else {
                // If a state value has already been selected add it to the new text field (in case you accidentally select the wrong country)
                if ($('.input_state_domestic').val() !== '0') {
                    $('.input_state_international').val($('.input_state_domestic').val());
                }
                thisForm.find('.input_state_domestic').removeClass('required').attr('disabled', 'disabled').hide().parents('.input_required_wrapper').hide();
                thisForm.find('.input_state_international').removeAttr('disabled').show();
            }
        });
    });
	
	// Alternate Product Images
	$('.product_image_alt').click(function(e){
		e.preventDefault();
		$('#product_image').children('img').attr('src', $(this).find('img').attr('src'));
	});
	
	//Firmware Signup
    $('#form_firmware_signup').submit(function(e) {
        e.preventDefault();
        if (generalFunctions.validateForm(this)) {
            $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                action: 'et_signup',
                jListID: $('#form_firmware_lid').val(),
                jEmail: $('#form_firmware_email').val()
            }, function (data) {
                switch (data.outcome) {
                    case '0':
        			var xmlDoc = $.parseXML(data.response);
        			generalFunctions.displayNotice(data.message + '<p>' + $(xmlDoc).find('error_description').text() + '</p>', '480');
        			break;
        			case '1':
        			generalFunctions.displayNotice(data.message, '480');
        			break;
                }
            });
        }
    });
});
