﻿var blogURLBase = 'http://blog.credera.com';

$(function(){
	Credera.buildTopNavMenu();
	Credera.addManualLinksToFooter();	        
	Credera.bindFancyboxLinks();
});


$.extend({
    getParamValue: function (paramName) {
        /// <summary>
        ///     Get the value of input parameter from the querystring
        /// </summary>
        /// <param name="paramName" type="String">The input parameter whose value is to be extracted</param>
        /// <returns type="String">The value of input parameter from the querystring</returns>
 
        parName = paramName.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
        var pattern = '[\\?&]' + paramName + '=([^&#]*)';
        var regex = new RegExp(pattern);
        var matches = regex.exec(window.location.href);
        if (matches == null) return '';
        else return decodeURIComponent(matches[1].replace(/\+/g, ' '));
    }
});

var Credera = Credera = Credera || {}; 	

Credera.buildTopNavMenu = function(){
	$('.credera-topnav li.static').each(function(){
	        var bkgdSpan = $('span.additional-background:first', this),
	            textSpan = $('span.menu-item-text', bkgdSpan),
	            itemName = textSpan.text()
	                               .replace(/\?/g,"")
	                               .replace(/\&amp\;/g,"&")
	                               .replace(/\&/g,"and")
	                               .replace(/ /g,"");
	        bkgdSpan.addClass('credera-topnav-staticitem-image ' + itemName);
	        textSpan.text('');
	  });
	  
	  $('#top_nav').fadeIn("fast");
};

Credera.twitterCallback2 = function(tweets) {
  var statusHTML = [];
  for (var i=0; i<tweets.length; i++){
    var username = tweets[i].user.screen_name;
    var status = tweets[i].text
    	.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      		return '<a href="'+url+'">'+url+'</a>';
    	});
    var tweetAge = Credera.relative_time(tweets[i].created_at);
    statusHTML.push('<a href="http://twitter.com/' + username + '/statuses/' + tweets[i].id_str + '">' + status + '<div class="date">' + tweetAge + '</div></a>');
  }
  
  var tweetboxText = statusHTML.join('');
  jQuery(document).ready(function ($) {
		$("#tweets > div.tweet").html(tweetboxText);
  });
};

Credera.relative_time = function(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
};

Credera.getCurrentSiteTitleForLandingPages = function() {
    var clientContext = new SP.ClientContext.get_current();
    var site = clientContext.get_web();   
    clientContext.load(site);
    clientContext.executeQueryAsync(
    	function() {	
    		Credera.currentSiteName = site.get_title();
    		$('#landingPageNavTitle').prepend(Credera.currentSiteName);
    		$('#landingPageNavTitle').wrap('<a href="' + document.location + '/../../">'); 
		},
		function(sender, args) { /* Do something if possible */ });
};


Credera.getSitePagesForLandingPages = function() {
    var clientContext = new SP.ClientContext.get_current();
    var myList = clientContext.get_web().get_lists().getByTitle('Pages');
    var query = new SP.CamlQuery();
    query.set_viewXml('<View Scope="RecursiveAll"><Query/></View>');
    var collListItems = myList.getItems(query);
    clientContext.load(collListItems, 'Include(Title,FileRef)'); 

	var navLinksHTML = '';

    // execute the actual query against the server, and pass the objects we have created to either a success or failure function 
    clientContext.executeQueryAsync(
    	function() {
		    var listItemEnumerator = collListItems.getEnumerator(); 
		
		    // loop through the list items 
		    while (listItemEnumerator.moveNext()) {
		        var oListItem = listItemEnumerator.get_current();
		        var link = '';
		        var title = '';		        
		        
	            title = oListItem.get_item('Title');
	            link = oListItem.get_item('FileRef');
				
				title = title.replace(' - Credera.com', '');
				
				if (Credera.currentSiteName != null &&  title.toLowerCase() != Credera.currentSiteName.toLowerCase())
		        {     
		        	var currentPageTitle = document.title;
		        	currentPageTitle = currentPageTitle.replace(' - Credera.com', '');
		        	
		        	if (title.toLowerCase() == currentPageTitle.toLowerCase())
		        	{		        
						navLinksHTML += "<li class='active'><a href='" + link + "'>" + title + "</a></li>";
					}
					else
					{		        
						navLinksHTML += "<li><a href='" + link + "'>" + title + "</a></li>";
					}

				}
		    }
		
		    $('#landingPageNavLinks').prepend(navLinksHTML);
		},
		function(sender, args) { /* Do something if possible */ });
};
        
Credera.randomFromTo = function(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
};


Credera.getSearchKeywords = function(){
	var keywords = $.getParamValue('k');
	
	$('#searchKeywords').html(keywords);
};


Credera.addManualLinksToFooter = function(){
	var manualBottomNavItems = '<li class="static"><a class="static menu-item" href="http://careers.credera.com"><span class="additional-background"><span class="menu-item-text">Careers</span></span></a></li>';               
    manualBottomNavItems += '<li class="static"><a class="static menu-item" href="' + blogURLBase + '/"><span class="additional-background"><span class="menu-item-text">Blogs</span></span></a></li>';
    manualBottomNavItems += '<li class="static"><a class="static menu-item" href="' + blogURLBase + '/category/news/"><span class="additional-background"><span class="menu-item-text">News</span></span></a></li>';
    manualBottomNavItems += '<li class="static"><a class="static menu-item" href="' + blogURLBase + '/category/events/"><span class="additional-background"><span class="menu-item-text">Events</span></span></a></li>';
    manualBottomNavItems += '<li class="static"><a class="static menu-item" href="' + blogURLBase + '/category/whitepapers/"><span class="additional-background"><span class="menu-item-text">White Papers</span></span></a></li>';
    manualBottomNavItems += '<li class="static"><a class="static menu-item" href="' + blogURLBase + '/category/casestudies/"><span class="additional-background"><span class="menu-item-text">Case Studies</span></span></a></li>';               
    $('.credera-bottomnav ul').append(manualBottomNavItems);    
}


Credera.addManualLinksToSiteMap = function(){
	var links = '';
	links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="http://careers.credera.com"> Careers</a></li>';
	links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="' + blogURLBase + '/"> Blogs</a></li>';
	links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="' + blogURLBase + '/category/news/"> News</a></li>';
	links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="' + blogURLBase + '/category/events/"> Events</a></li>';
	links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="' + blogURLBase + '/category/whitepapers/"> Whitepapers</a></li>';
		links += '<li><img src="/_wpresources/QuestechSystems.SharePoint.Publishing.SiteMapWebPart/1.0.0.0__079e23e300376e5b/images/node.gif"><a href="' + blogURLBase + '/category/casestudies/"> Case Studies</a></li>';
	
	$('#siteMap ul').append(links);
};


Credera.bindFancyboxLinks = function (){

	// attach to YouTube videos for any <A> tag that is set to open in new window
	// (YouTube URLs must have the "v" parameter as the first in the querystring, immediately after the "?")
	$('#s4-bodyContainer a[href*="youtube.com/watch"][target="_blank"]').click(function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'title'			: this.title,
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + "&fs=1",
				'type'			: 'swf',
				'swf'			: {'wmode' : 'transparent', 'allowfullscreen' : 'true'}
			});

		return false;
	});
	
	$('#s4-bodyContainer a[href*="vimeo.com"][target="_blank"]').click(function() {
		$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'title'			: this.title,
				'href'			: this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),
				'type'			: 'swf',
				'swf'			: {'wmode' : 'transparent', 'allowfullscreen' : 'true'}
			});

		return false;
	});

};


//fix SP2010 scrolling issues for internet sites with no ribbon
//see http://kyleschaeffer.com/sharepoint/sharepoint-2010-scrolling/
function FixRibbonAndWorkspaceDimensions(){
  ULSxSy:;
  g_frl = true;
  var elmRibbon = GetCachedElement("s4-ribbonrow");
  var elmWorkspace = GetCachedElement("s4-workspace");
  var elmTitleArea = GetCachedElement("s4-titlerow");
  var elmBodyTable = GetCachedElement("s4-bodyContainer");
  if(!elmRibbon || !elmWorkspace || !elmBodyTable){
    return;
  }
  if (!g_setWidthInited){
    var setWidth = true;
    if (elmWorkspace.className.indexOf("s4-nosetwidth") > -1)
      setWidth = false;
    g_setWidth = setWidth;
    g_setWidthInited = true;
  }
  else{
    var setWidth = g_setWidth;
  }
  var baseRibbonHeight = RibbonIsMinimized() ? 44 : 135;
  var ribbonHeight = baseRibbonHeight + g_wpadderHeight;
  if(GetCurrentEltStyle(elmRibbon, "visibility") == "hidden"){
    ribbonHeight = 0;
  }

  // Override default resizing behavior
  // -- adds padding to the top of the "s4-workspace" <div> if the ribbon exists and has content
  // -- allows the ribbon to be positioned using CSS instead of JavaScript (more accessible)
  // -- checks to see if the page is inside a "no-ribbon" dialog
  if(elmRibbon.children.length > 0 && document.getElementsByTagName("html")[0].className.indexOf('ms-dialog-nr') == -1){
    elmWorkspace.style.paddingTop = ribbonHeight + 'px';
  }
}
