/*
	gadget-lib.js
	
	Javascript library for Google-gadget based pages for Mobile Case and Launchpad
*/

function find_gadget(id) {
  for (var i = 0; i < launchpad.gadgets.length; i++) {
    if (launchpad.gadgets[i].id == id) {
      return launchpad.gadgets[i];
    }
  }

  // put some sort of "can't find" code here
  alert("Unknown gadget '" + id + "'");
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function adjustHeight(sizeInPx) {
  document.getElementById(this.f).style.height = sizeInPx + 'px';
}

function display_gadget(id, is_mobile, width, height) {

  var g_def = find_gadget(id);

  var protocol = 'http';
  if (location.protocol == 'https:') {
    protocol = 'https';
  }

  // check for gadget height override
  var height = 175;
  if (g_def.height) {
    height = g_def.height;
  }

  var sb = [];

  sb[sb.length] = '<div class="gadget_container" id="portlet_' + id + '">';
  
  if (g_def.full_url) {
    sb[sb.length] = '<div class="gadget_title"><a style="text-decoration:none; color: white;" href="' + g_def.full_url + '" target="_blank">' +  g_def.title + ' <img style="margin-top: 2px;" src="img/linkout.png" width="12" height="12" border="0"/></a>';
  } else {
    sb[sb.length] = '<div class="gadget_title">' + g_def.title + '<img style="margin-top: 2px;" src="img/nolinkout.png" width="12" height="12" border="0"/>';    
  }
  
  if (is_mobile) {
  	sb[sb.length] = '<div class="gadget_title_mobile_link"><a href="http://m.case.edu/">Case Mobile</a></div>';
  }
  
  sb[sb.length] = "</div>";
  
  // is this a gadget from google (has a gg_url) or are we just displaying a web 
  // page (has a link)?  
  if (g_def.gg_url) {

		var gg_params = [];
		
		// get hardcoded params from the gadget definition
		if (g_def.gg_param) {
			gg_params[gg_params.length] = g_def.gg_param.join("&");
		}
		
		// also pass though any parameters specified in the browser URL
		var url_params = window.location.search.substring(1).split('&');
		for (i=0; i<url_params.length; i++) {
			gg_params[gg_params.length] = "up_" + url_params[i];
		}

		var gg_param_str = "&up_wintophref=" + escape(window.top.location.href);
		if (is_mobile) {
			gg_param_str += "&up_ismobile=1";
		}
	
		if (gg_params.length > 0 ) {
			gg_param_str += "&" + gg_params.join("&");
		}
				
    sb[sb.length] = '<iframe id="gadget_frame_' + id + '" name="gadget_frame_' + id + '" src="http://open.gmodules.com/gadgets/ifr?nocache=1&container=open&mid=1&lang=all&country=ALL&view=home&url=';

    sb[sb.length] = encodeURIComponent(g_def.gg_url);
    sb[sb.length] = '&source=' + protocol + '%3A%2F%2Fwww.case.edu&parent=' + protocol + '%3A%2F%2Fwww.case.edu&libs=core%3Acore.io'+gg_param_str+'" style="display: block;" scrolling="auto" width="' + width + '" frameborder="0" height="' + height + '"></iframe>';
  } else {
    sb[sb.length] = '<iframe id="link_frame_' + id + '" name="link_frame_' + id + '" ';
    sb[sb.length] = 'src="' + g_def.link_url + '" ';
    sb[sb.length] = 'style="display: block;" scrolling="auto" width="' + width + '" frameborder="0" height="' + height + '"></iframe>';
  }

  sb[sb.length] = "</div>";

  return sb.join("");
}

function display_gadget_icon(id, is_mobile) {
  var sprite_pic = new Image();
  sprite_pic.src = launchpad.sprite.url;

  var sb = [];

  var target;
  if (is_mobile) {
    target = "";
  } else {
    target = ' target="_blank" ';
  }

  sb[sb.length] = '<div class="icon">';

  if (id == "blank") {
    sb[sb.length] = '<div class="icon_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: -12px 0px; background-repeat:no-repeat;"></div>';
    //sb[sb.length] = '<div class="icon"><img class="icon_img" src="'+launchpad.iconurl+'blank.png" border="0" alt="" /></div>';
    //alert('blank');
    sb[sb.length] = '</div>';

    return sb.join("");
  }

  var g_def = find_gadget(id);
  
  
  var gadget_page = "gadget";
  if (g_def.scale == "no" && isIphone() ) {
  	gadget_page = "gadgetns	";
  }
  
  if (g_def.auth && g_def.auth == "yes") {
    gadget_page = gadget_page + "_s";
  }

  if (g_def.gg_url) {
    sb[sb.length] = '<a href="' + gadget_page + '.html?gid=' + id + '"' + target + 'onClick="recordOutboundLink(this, \'Gadgets\', \''+g_def.id+'\', false);return false;">';
  } else if (g_def.link_url) {
    sb[sb.length] = '<a href="' + g_def.link_url + '"' + target + ' target="_blank" onClick="recordOutboundLink(this, \'Gadgets\', \''+g_def.id+'\', true);return false;">';
  } else {
    sb[sb.length] = '<a href="#">';
  }

  if (!g_def.sprite) {
    if (g_def.icon == "") {
      sb[sb.length] = '<img class="icon_img" src="' + launchpad.iconurl + 'case.png" border="0" alt="" />';
    } else {
      sb[sb.length] = '<img class="icon_img" src="' + launchpad.iconurl + g_def.icon + '.png" border="0" alt="" />';
    }
  } else {
    sb[sb.length] = '<div class="icon_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: ' + ((g_def.sprite.left * -1 * launchpad.sprite.icon.width) - (launchpad.sprite.attribute.width * launchpad.sprite.attribute.cols)) + 'px ' + (g_def.sprite.top * -1 * launchpad.sprite.icon.height) + 'px; background-repeat:no-repeat;"></div>';
  }
  if (!g_def.gg_url && g_def.link_url) {
    sb[sb.length] = '<div class="linkout_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: 0px -23px; background-repeat:no-repeat;"></div>';
  } else {
    sb[sb.length] = '<div class="linkout_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: 0px 0px; background-repeat:no-repeat;"></div>';
  }

  if (g_def.auth && g_def.auth == "yes") {
    sb[sb.length] = '<div class="lock_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: 0px -35px; background-repeat:no-repeat;"></div>';
  } else {
    sb[sb.length] = '<div class="lock_sprite" style="background-image: url(' + sprite_pic.src + '); background-position: 0px -0px; background-repeat:no-repeat;"></div>';
  }

  if (g_def.title_short) {
    sb[sb.length] = g_def.title_short;
  } else {
    sb[sb.length] = g_def.title;
  }

  sb[sb.length] = '</a></div>';

  return sb.join("");
}



function display_key() {
  var sprite_pic = new Image();
  sprite_pic.src = launchpad.sprite.url;
  var sb = [];
  sb[sb.length] = '<div style="display: table; margin: 0 auto;">';
  sb[sb.length] = '<div style="display: table-cell; float: left; width: 12px; height: 12px; background-image: url(' + sprite_pic.src + '); background-position: 0px -35px; background-repeat:no-repeat;"></div>';
  sb[sb.length] = '<div style="display: table-cell; float: left;">&nbsp;- Requires Login</div>';
  sb[sb.length] = '<div style="display: table-cell; float: left; color: #005696;">&nbsp;&nbsp;|&nbsp;&nbsp;</div>';
  sb[sb.length] = '<div style="display: table-cell; float: left; width: 12px; height: 12px; background-image: url(' + sprite_pic.src + '); background-position: 0px -11px; background-repeat:no-repeat;"></div>';
  sb[sb.length] = '<div style="display: table-cell; float: left;">&nbsp;- Link</div>';
  sb[sb.length] = '</div>';
  return sb.join("");
}


/*
 * Google Analytics outbound link tracking code
 *   See http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55527
 */
function recordOutboundLink(link, category, action, newtab) {
  try {
    var pageTracker=_gat._getTracker("UA-620392-12");
    pageTracker._trackEvent(category, action);
    if (newtab) {
    	window.open(link.href);
    } else {
		  document.location = link.href;
  	}
  }catch(err){}
}


/*
* Cookie Handling
*   from http://techpatterns.com/downloads/javascript_cookies.php
*/

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
		
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +	
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


/* Browser Detection Functions */
function isWindowsMobile() {
	var ua = navigator.userAgent;
	if (ua.indexOf("MSIE") == -1) { return false; }
	if (ua.indexOf("Windows CE") != -1) { return true; }
	if (ua.indexOf("PPC") != -1) { return true; }
	if (ua.indexOf("Smartphone") != -1) { return true; }
	return false;
}

function isIphone() {
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
		return true;
	}
	
	return false;
}

;

