// Global vars
// Initial AJAX array setup

var downloadQueue = new Array();

// used to detect which link the user is currently animating to or at.
var toLink;

// single string used if the user clicks a new link while a new page is animating in. The new page then animates using this var.
var linkQueue;

// used when a link was clicked before loaded. this will tell the loader to call the page change after it does load.
var loadingQueue;

// used to remove the current page from the loading queue
var currentPage;

// stores last clicked link
var clickedLink;

var NAV_ANIM_SPEED = 100;
var navLinkHeight = 0;

var userBrowser = $.browser;
var userBrowserVersion = $.browser.version;
var userIsOlderIE = userBrowser.msie && userBrowserVersion < 8.0;

$(function() {
	
	
	// Set a margin fix for the first page
	$('#core_container').height($('#core_container').height() - 40);
	// Set margin on container to compensate for footer
	$('#core_container').css('margin-bottom', $('#footer_container').height());
	// Set margin for footer based on its height
	$('#footer_container').css('margin-top', -($('#footer_container').height() + 2));
	
	
	// Before we sizeBackground lets remove the page content so we can be sure no scrollbars exist
	$('#core_container').hide();
	$('#header_photo').sizeBackground().show();
	$('#core_container').show();
	
	// Header background should resize with window
	$(window).resize(function (event) {
		$('#header_photo').sizeBackground();
	});
	
	// Init nav
	$('#nav a').add('#logo a').click(function(e) {
		e.preventDefault();
		var link = $(this).attr('href');
		clickedLink = link;
		//console.log('\n##### ' + link + ' PRESSED #####');
		if (checkState() != link) {
			//console.log('  Link isn\'t current location, changing URL...');
			History.pushState(null, null, link);
		} else {
			//console.log('  Link is already the active page. Click ignored.')
		}
	});
	
	
	$page = $(this);
	
	// Current page is the first into the queue
	downloadQueue.push(checkState());
	
	// Homepage is 2nd into the queue
	downloadQueue.push($('#logo a').attr('href'));
	
	// Load top level pages into the queue
	$('#nav > li > a').each(function(index) {
		downloadQueue.push($(this).attr('href'));
	});
	
	// Next, load lower lever pages into queue
	$('.subnav > li > a').each(function() {
		// Only add this page to the queue if it isn't already in there to avoid loading in the same page twice
		// (The Careers page is linked to in two sub menus)
		if (!downloadQueue.contains($(this).attr('href'))) {
			downloadQueue.push($(this).attr('href'));
		}
	});
	
	/*
		Remove the current page from the queue
	*/
	var currentIndex = 0;
	if (window.location.hash && window.location.hash != '#/') {
		// If user visited with a hash link, check that first
		currentPage = checkState();
		//console.log('User is visiting from hash: ' + window.location.hash);
		
		// Splice the current page out of the queue (the duplicate only)
		var o = 0;
		for (var $i = 0; $i < downloadQueue.length; $i++) {
			if (downloadQueue[$i] == currentPage) {
				o++;
				// Only remove the 2nd case
				if (o == 2) {
					// Remove from queue
					downloadQueue.splice($i, 1);
					// Continue if not visiting from a hard link AND a hash link
					if (window.location.pathname == '/') {
						// Add the page to the loading queue
						loadingQueue = currentPage;
						break;
					}
				}
			}
		}
	} else {
		// If user visited from a hard link, check that
		//console.log('User is visiting from a hard link.');
		$('.subnav').each(function(index) {
			// First check to see if any subnav items are open
			$(this).children('li').each(function(index) {
				if($(this).children('a.open').length > 0) {
					currentPage = $(this).children('a').attr('href');
				}
			});
		});
		// If there wasn't an open link in the subnav, check the primary nav
		if (currentPage == null) {
			$('#nav > li').each(function(index) {
				if($(this).children('a.open').length > 0) {
					currentPage = $(this).children('a').attr('href');
				}
			});
			if (currentPage == null) {
				currentPage = '/'
			}
		}
		// Splice the current page out of the queue
		for(var $i = 0; $i < downloadQueue.length; $i++) {
			if(downloadQueue[$i] == currentPage) {
				// Remove from queue
				downloadQueue.splice($i, 1);
				break;
			}
		}
	}
		
	// Begin loading
	loadPages();
	
	// Init nav links in footer
	$('#footer').initPageContents();
	
});

$(window).load(function() {
	
	// Init subnavs
		checkAndInitSubnavs();
	revealNav();
	
});


function revealNav () {
	
	$nav = $('#nav');
	
	$nav.show();
	$nav.children().css('top', ($nav.children().children('a').not('.open').outerHeight(true)+6) * -1);
	
	// Lets animate each nav item in one-by-one
	navItemsLength = $nav.children().length - 1;
	animateNavItem(0, navItemsLength);
	
}


function animateNavItem (current, total) {
	var $thisItem = $('#nav').children().eq(current);
	
	if (current > 0) {
		// Set a timeout before running animation
		setTimeout(function() {
			$thisItem.animate({
				top: -26
			}, 1000, 'easeOutElastic', function() {
				if ($thisItem.children('a.open').length > 0) {
					// This nav item is currently open (being hit directly by URL)
					if ($thisItem.children('.subnav').is(':visible')) {
						// Don't try to open it again. It is already.
					} else {
						activateNavItem($thisItem.children('a'));
					}
				}
				if (current == total) {
					// Browser reports the nav as still animating here, even though it's at the end-of-animation function. A timeout is set to correct this.
					setTimeout(function() {
						// After animating, check to see if the user has clicked a new link
						//console.log('\n##### Initial main nav animation complete. #####\nChecking to see if a new link was pressed...\n');
						if (clickedLink) {
							//console.log('  Clicked link found. Changing...');
							changeNavAndPage();
						} else {
							//console.log('  Nothing detected.');
						}
					}, 100);
				}
			});
			if (current < total) {
				animateNavItem(current + 1, total);
			}
		}, 200);
	} else {
		// This is the first item to be animated, do animation immediately
		$thisItem.animate({
			top: -26
		}, 1000, 'easeOutElastic', function() {
			if ($thisItem.children('a.open').length > 0) {
				// This nav item is currently open (being hit directly by URL)
				if ($thisItem.children('.subnav').is(':visible')) {
					// Don't try to open it again. It is already.
				} else {
					activateNavItem($thisItem.children('a'));
				}
			}
		});
		if (current < total) {
			animateNavItem(current + 1, total);
		}
	}
	
}


function checkAndInitSubnavs () {
	// Check if we need to re-init subnav items
	$navLinks = $('#nav > li > a');
	//console.log(navLinkHeight, $('#nav a').height())
	if (navLinkHeight != $('#nav a').height()) {
		// User's font-size has changed
		$navLinks.each(function(i) {
			$subnav = $(this).parent().children('.subnav');
			if ($subnav.length > 0) {
				//alert('about to run initSubnav' + $(this).attr('href'));
				initSubnav($subnav);
			}
		});
		
		// Store the new font-size
		navLinkHeight = $('#nav a').height();
	}
}


function activateNavItem ($a) {
	//alert('about to run checkAndInitSubnavs');
	checkAndInitSubnavs();
	//alert('just finished checkAndInitSubnavs');
	//console.log('doesnt get here.... activateNavItem()')
	$li = $a.parent();
	$subnav = $li.children('.subnav');
	
	// Nav item: Slide down and fade color
	if ($a.filter('.open').length < 1) $a.toggleClass('open', NAV_ANIM_SPEED);
	
	// Subnav: Check if one exists
	if ($subnav.length > 0) {
		// Slide down subnav
		toggleSubnav($subnav, NAV_ANIM_SPEED);
	}
	
}


function deactivateNavItem ($a) {
		
	$li = $a.parent();
	$subnav = $li.children('.subnav');
	
	// Nav item: Slide down and fade color
	$a.toggleClass('open', NAV_ANIM_SPEED);
	
	// Subnav: Check if one exists
	if ($subnav.length > 0) {
		// Slide up subnav
		toggleSubnav($subnav, NAV_ANIM_SPEED);
	}
	
}


function toggleSubnav ($subnav, animSpeed) {
	var opening = true;

	if ($subnav.is(':visible')) {
		opening = false;
	}

	$subnav.show();

	animEndY = $subnav.position().top;

	animStartY = ($subnav.outerHeight(true) + $('#nav').outerHeight(true)) * -1;


	if (opening) {
		//console.log('    Subnav animation [opening subnav for ' + $subnav.parent().children('a').attr('href') + '] started...');
		// OPENING

		// Set css for animation start
		$subnav.css({
			top: animStartY,
			opacity: 0.0
		});
		
		// Run animation
		$subnav.animate({
			top: animEndY,
			opacity: 1.0
		}, animSpeed * 3, function() {
			// After animating, check to see if the user has clicked a new link
			//console.log('\n##### Subnav animation [opening subnav for ' + $subnav.parent().children('a').attr('href') + '] complete. #####\nChecking to see if a new link was pressed...\n'); //Details: ' + $(this).attr('style'));
			if (clickedLink) {
				//console.log('  Clicked link. Changing...');
				changeNavAndPage();
			} else {
				//console.log('  Nothing detected.');
			}
		});
	} else {
		//console.log('    Subnav animation [closing subnav for ' + $subnav.parent().children('a').attr('href') + '] started...');
		// CLOSING
		
		// Run animation
		$subnav.animate({
			top: animStartY,
			opacity: 0
		}, animSpeed * 3, function() {
			// Restore css to how it was before this dropdown was ever opened
			$subnav.css({
				top: animEndY
			}).hide();
			
			// After animating, check to see if the user has clicked a new link
			//console.log('\n##### Subnav animation [closing subnav for ' + $subnav.parent().children('a').attr('href') + '] complete. #####\nChecking to see if a new link was pressed...');
			if (clickedLink) {
				//console.log('  Clicked link. Changing...');
				changeNavAndPage();
			} else {
				//console.log('  Nothing detected.');
			}
		});
	}
}


function initSubnav ($subnav) {
	
	//console.log ('initSubnav : ',$subnav);
	
	// Clear styles
	$subnav.add($subnav.find('li')).removeAttr('style');
	
	// Find corresponding nav link
	$navLink = $subnav.parent().children('a');
	
	// Find main nav
	$nav = $subnav.parent().parent();
	
	// Get width of ul
	// Lock width of each li to the width of ul
	// Set each li to display: inline-block
	ogUlWidth = $subnav.width();
	$subnav.find('li').width(ogUlWidth).css({
		'display' : 'inline-block',
		'*display' : 'inline',
		'zoom' : 1,
		'float' : 'left'
	});
	// Now lock the width of the ul to its original width
	$subnav.width(ogUlWidth);
	
	
	// See if the ul is too tall
	acceptableHeight = $('#header_container').height() - ($nav.height() + $nav.children().position().top ) - 20;
	
	while ($subnav.height() > acceptableHeight) {
		// Double the width of $subnav
		$subnav.width($subnav.width() * 2);
	}
	
	if ($navLink.filter('.open').length > 0) {
		// This item is currently open (page being hit directly by URL)
		topDiff = 0;
	} else {
		topDiff = 6;
	}
	$subnav.css('top', $navLink.outerHeight(true) + topDiff);
	
	
	if ($navLink.outerWidth(true) >= $subnav.width()) {
		//console.log('nav item is wider than or equal to subnav');
		// Nav item is wider than or equal to subnav
		// Fix subnav to width of nav item
		$subnav.find('li').add($subnav).width(Math.floor($navLink.outerWidth(true)));
		// Also fix width of navLink to exact same as subnav, fixes FF problem with partial pixels
		// Disabled by Gareth on 02/28  //$navLink.width(Math.floor($navLink.width()));
	} else {
		// Subnav is going to be larger than its parent nav item
		
		// If this is the last nav item, we can just align it right:0
		if ($navLink.parent().index() == $navLink.parent().siblings().length) {
			// Last item in main nav
			$subnav.css('right', 0);
			$subnav.css('left', 'auto');
		} else {
			// Start by centering it below its nav item
			subnavLeftPos = Math.ceil((($subnav.outerWidth(true) - $navLink.outerWidth(true)) / 2) * -1);
			$subnav.css('left', subnavLeftPos);
		
			// Now make sure the right edge is not beyond the right edge of the main nav
			$subnav.show();
			subnavRightEdge = Math.ceil($subnav.offset().left + $subnav.outerWidth(true));
			$subnav.hide();
			navRightEdge = Math.ceil($nav.offset().left + $nav.outerWidth(true));
			
			edgeDiff = Math.ceil(subnavRightEdge - navRightEdge);
		
			if (edgeDiff > 0) {
				// It extends beyond the right edge of the main nav
				// Move it back a bit
				$subnav.css('left', subnavLeftPos - edgeDiff);
			}
		}
		
	}
}





(function ($) {	
	// Initialize any JS necessary for the contents of a page
	$.fn.initPageContents = function () {
		
		// Make sure this page hasn't already been init'd
		if ($(this).data('initComplete')) {
			return;
		}
		// Mark this as init'd so we won't do it twice later
		$(this).data('initComplete',true);
		
		// Crawl for links, activate any inter-site links
		$(this).find('a').each(function() {
			if ($(this).attr('href').substr(0,1) == '/') {
				$(this).click(function(e) {
					e.preventDefault();
					$(this).activateLink(true);
					if (checkState() != $(this).attr('href')) {
						//console.log('  Link isn\'t current location, changing URL...');
						History.pushState(null, null, $(this).attr('href'));
					} else {
						//console.log('  Link is already the active page. Click ignored.')
					}
				});
			}
		});
		
		// Specific operations to be run only on certain pages
		switch ($(this).attr('id')) {
			
			case 'home':
				TwitterAPI.Statuses.user_timeline("curiousmindsinc", 5, function(json){
					var content = '';
					$.each(json, function(i){
						var tweet = this['text'];
						content += '<div class="twitter-post"><p>' + replaceURLWithHTMLLinks(tweet) + '</p></div>';
					});
					$('#twitter_feed_items').empty().append(content);
				});
				
				// Make sure img tags in .blog-post aren't wider than the right column
				$('.blog-post img').each(function() {
					if ($(this).width() > 250) {
						$(this).removeAttr('height').width(250);
					}
				});
				
				break;
			
			case 'intro_careers':
				$positionsToc = $('#positions_toc_container');
				
				// Activate toc links to scroll to position descriptions
				$positionsToc.find('a').click(function(e) {
					e.preventDefault();
					$.scrollTo(('#' + $(this).attr('href').substr(1)), 400, {offset: {top:-20, left:0}});
				});
				
				// Fix toc container
				var top = $positionsToc.offset().top - parseFloat($positionsToc.css('marginTop').replace(/auto/, 0));
				$(window).scroll(function (event) {
					// what the y position of the scroll is
					var y = $(this).scrollTop();

					// whether that's below the form
					if (y >= top) {
						// if so, ad the fixed class
						$positionsToc.addClass('fixed');
					} else {
						// otherwise remove it
						$positionsToc.removeClass('fixed');
					}
				});
				break;
				
  		case 'companies':
          $(".logo").hover(function() {
            $(this).find("span").stop().animate({opacity:1.0}, 200);
          }, function() {
            $(this).find("span").stop().animate({opacity:0.0}, 500);
          });        
			  break;
			
			case 'contact_location':
				// Load the Google map
				
				// THIS TRY/CATCH BLOCK DIDN'T REALLY WORK: In WebKit browsers, for some reason, we always ended up in the catch block, even when no errors should have been happening.
				// Worked fine in FF though. Hmmmm....... For now I'll just comment it all out
				// try {
				// 	initialize();
				// } catch (error) {
				// 	$('#map_canvas').html('<p style="text-align:center;"><br/><br/><br/><br/><br/><br/><br/>You seem to be using a browser or plugin that is blocking Google Maps. Disable this plugin or use a different browser and try again.</p>');
				// }
				initialize();
				
				// Setup the route details buttons (Clicking one button shows the directions; hides the other directions)
				$('.location-button').each(function() {
					$(this).click(function(e){
						e.preventDefault();
						if($(this).next().hasClass('hidden')) {
							// Selected one is currently hidden
							
							// Close the currently open one
							$(this).siblings('ol:not(.hidden)').prev().removeClass('open').next().toggleClass('hidden', NAV_ANIM_SPEED * 2);
							// $(this).siblings('ol').each(function() {
							// 	if(!$(this).hasClass('hidden')) {
							// 		$(this).toggleClass('hidden', NAV_ANIM_SPEED * 2);
							// 	}
							// });
							
							// Open the selected one
							$(this).addClass('open');
							$(this).next().toggleClass('hidden', NAV_ANIM_SPEED * 2, function() {
								$('#core_container').height($('#core_container').height());
							});
							$('#core_container').css('height', '');
						}
					});
				});
			break;
		}
	}
	
	$.fn.activateLink = function (scrollToTop) {
		var link = $(this).attr('href');
		// As long as the page isn't animating and you're not clicking on the page you're currently on, switch pages
		if ($('.page_content:animated').length == 0 && ($('#core_container').children(':first-child').attr('id') !== link.replace('/', '').replace(/\//gi, '_'))) {
			//Begin attempt to switch to new page
			toPage(link);
		} else if ($('.page_content:animated').length > 0 && link !== toLink) {
			// If you are animating, but you're not clicking on the link you're animating to, queue up the page you clicked
			linkQueue = link;
		}
		
		// Lets scroll to the top of the core container if we need to
		if (scrollToTop && $('#core_container').offset().top < $(window).scrollTop()) {
			$.scrollTo($('#core_container'), 400, {easing: 'easeInExpo'});
		}
		
	}
	
}(jQuery));






// AJAX loading function
var currentPageNum = 0;
function loadPages() {
	if(currentPageNum < downloadQueue.length) {
		$.ajax({
			url: downloadQueue[currentPageNum] + "?ajax=1",
			success: function(content) {
				$('#page_bin').append(content);
			},
			error: function() {
			},
			complete: function(content) {
				currentPageNum++;
				if(loadingQueue) {
					toPage(loadingQueue);
					loadingQueue = null;
				}
				//setTimeout('loadPages()', 3000); // For testing
				loadPages();
			}
		});
	}
}

/*
	Detect when the address changes,
	Change nav links
*/
var firstVisit = true;
(function(window, undefined) {
	var History = window.History;
	$(window).bind('statechange', function() {
		//console.log('\n  ##### CHANGE STATE DETECTED #####');
		if (!firstVisit) {
			changeNavAndPage();
		} else {
			// This runs if the user has just opened the site before clicking any links
			firstVisit = false;
			//console.log('  Initial change state ignored. Checking nav for non-Home link...');
			
/*
			// Check to see if the page isn't Home
			if (checkState() !== '/') {
				var initialState = checkState();
				var $initialLink;
				// Setup the nav for the visited link
				$('#nav').find('a').each(function() {
					if($(this).attr('href') == initialState) {
						$initialLink = $(this);
						//console.log('  Found ' + $initialLink.attr('href'));
					}
				})
				if ($initialLink) {
					toPage($initialLink.attr('href'));
				} else {
					//console.log('  Staying on page. (Current URL not found in nav.)');
				}
			} else {
				//console.log('  On homepage.');
			}
*/
		}
	});
})(window);

function changeNavAndPage() {
	//console.log('\n    ##### CHANGE NAV AND PAGE #####');
	var state = checkState();
	var navLinkHref = state;
	//console.log('    State: ' + state);
	var $selectedLink;
	// Find nav item just pressed
	if (navLinkHref.substr(0,5) == '/blog') {
		navLinkHref = navLinkHref.substr(0,5);
	}
	$('#header_contents').find('a').each(function(){
		if ($(this).attr('href') == navLinkHref) {
			$selectedLink = $(this);
			//console.log('    Found pressed link: ' + $(this).attr('href'));
		}
	});
	// As long as the nav items aren't animating, add the functionality
	if($('#nav > li:animated').length == 0) {
		//console.log('      Nav items are *not* animating.');
		var isAnimating = false;
		//console.log('      Checking subnavs for animation...');
		$('.subnav').each(function(i) {
			if ($(this).is(':animated')) {
				isAnimating = true;
				//console.info('        **animating ' + $(this).parent().children('a').attr('href') + '**');
			}
		});
		//console.log('      Checking subnav links for animation...');
		$('.subnav').find('li > a').each(function(i) {
			if ($(this).is(':animated')) {
				isAnimating = true;
				//console.info('        **animating ' + $(this).parent().children('a').attr('href') + '**');
			}
		});
		if (!isAnimating) {
			//console.log('        Subnav & links are *not* animating.');
			if ($selectedLink.hasClass('open')) {
				//console.log('  This item is open.');
				// This item is open
				// If this is a top level item and has a subnav, make sure all subnav items are deactivated
				if ($selectedLink.parent().parent().attr('id') == 'nav' && $selectedLink.parent().find('.subnav').length > 0) {
					// Find subnav anchors that are open
					$selectedLink.parent().find('.subnav a.open').each(function() {
						deactivateNavItem($(this));
					});
				}
			} else {
				//console.log('    Deactivating any currently open siblings.');
				// Deactivate any currently open siblings
				$openSibling = $selectedLink.parent().siblings().find('a.open');
				if ($openSibling.length > 0) {
					// A different item is open--so close it
					deactivateNavItem($openSibling);
				}
				//console.log('    Activating selected link.');
				if ($selectedLink.parent().attr('id') != 'logo') {
					activateNavItem($selectedLink);
				}
			}
			/*
				Page changing
			*/
			// Save the HREF for when (this) changes
			//console.log('    Page changing to: ' + $selectedLink.attr('href'));
			$selectedLink.activateLink();
		} else {
			//console.log('      **Subnav and/or subnav links animating.** (Link ' + checkState() + ' queued)');
		}
	} else {
		//console.log('    Nav items are animating...');
	}
}


// Switch page function
function toPage(link) {
	//console.group('toPage(' + link + ')');
	// Save the link you're animating to
	toLink = link;
	// Calculate the current page's height
	var currentPageHeight = $('#core_container').height();
	// Set the #core_container height to the current page's height
	$('#core_container').height(currentPageHeight);
	// Save the new page's ID (not as an object) by replacing /category/page with #category_page
	var newPageID = '#' + link.replace('/', '').replace(/\//g, '_');
	if (newPageID == '#') {
		newPageID = '#home';
	}
	// Check the bin for the page you're trying to load
	if($('#page_bin').children(newPageID).length) {
		/*
			If it's in the bin, load it up
		*/
		//console.log('Found ' + newPageID + ' in the bin. Loading...');
		// Append the new page to #core_container
		$(newPageID).appendTo('#core_container');
		// Animate the old page up
		$('#core_container').children(':first-child').animate({
			marginTop: -(currentPageHeight + 40)
		}, 1000, 'easeInOutExpo', function() {
			// After animating, put old page back in bin and reset margin
			$('#core_container').children(':first-child').appendTo('#page_bin').css('margin-top', 0);
			// Then, check to see if another link has been queued
			if (linkQueue) {
				toPage(linkQueue);
				linkQueue = null;
			} else {
				// No other pages queued, make sure the current showing page is init'd and good to go
				$(newPageID).initPageContents();
			}
		});
		// Animate #core_container height to new page height
		$('#core_container').animate({
			height: $(newPageID).height()
		}, 1000, 'easeInOutExpo');
	} else {
		/*
			If it's not in the bin, push it to the top of the queue
		*/
		//console.log(newPageID + ' *not* found in the bin. Pushing to top of queue...');
		// Find the requested link in the queue
		for(var i = 0; i < downloadQueue.length; i++) {
			if(downloadQueue[i] == link) {
				// Remove from queue
				downloadQueue.splice(i, 1);
				// Re-add to the next queue position
				downloadQueue.splice(currentPageNum, 0, toLink);
				loadingQueue = toLink;
				//console.log(link + ' now at the top of the queue.');
				break;
			}
		}
	}
	//console.groupEnd();
}

// Load Google Maps
function initialize() {
	var latlng = new google.maps.LatLng(34.093158, -118.378161);
	var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel:false
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	var marker = new google.maps.Marker({
		position: latlng, 
		map: map, 
		title:"Curious Minds"
	});
}

function checkState() {
	if (History.getState()) {
		return History.getState().url.replace(window.location.protocol + '//' + window.location.host, '');		
	} else {
		//console.warn('No history to return. Returning data: /.');
		return '/';
	}
}





Array.prototype.contains = function(value) {

	for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
		if (this[i] == value) {
			return true;
		}
	}
	
	return false;

};




TwitterAPI = {
	Statuses: {
		user_timeline:function(screen_name, count, callback){
			jQuery.getJSON("http://twitter.com/statuses/user_timeline/" + screen_name + ".json?count="+count+"&b="+Math.random()+"&callback=?",
			callback);
		}
	}
};


function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1'>$1</a>"); 
}


