/*
* Created By: Zoe Ng
* Created Date: 12/28/2008
*/

var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1
// On Document ready function
$(document).ready(function(){
		imageMouseover.init();
   
	    handleContentSlider();
        applyCSSStyle();
        // set left nav base on the top level html and sub level A tag
        //setLeftNav("submenu Item 2", "submenu item 2 2");
        buildAccordion();
        addFieldOnOffEvent();
        createCharCounter();
        ImgRollover.init();
        $(".tabs").tabs();
        if (isIE6) {
        	ie6MouseoverEvent();
		}	
        addPdfTrackEvent();
		quoteTextResize.init(); 	
		COMMON_tabs_display.init();
});


  var imageMouseover = function () {
    return {
      init: function () {
        $('img').mouseover( function () {
        	var src = $(this).attr('src');
        	// only do the mouseover if filename already contains _off
			if (src.search(/_off/g)>-1) {
          		$(this).attr('src', src.replace(/_off/g, '_on'));
          		// add class as indicator mouseover activated
          		$(this).addClass('imageMouseover');
        	}
        });
        $('img').mouseout( function () {
			var src = $(this).attr('src');
			// only do if filename has _on AND mouseover was activated by imageMouseover function
        	if (src.search(/_on/g)>-1 && $(this).hasClass('imageMouseover')) {			        	
          		$(this).attr('src', src.replace(/_on/g, '_off'));
        	}
        });
      }
    };
  }();


	var quoteTextResize = function () {
		return {
			init: function () {
				$('div.quoteBlock div.arrowBlock_bottom').each( function () {
					var quoteImage = $(this).siblings('div.quoteImage');
					var imageWidth = 0;
					if (quoteImage.length) {
						imageWidth = quoteImage.children('img').width();						
					}

					var quoteBlock = $(this).parents('div.quoteBlock');
					var contentContainer = $(this).parents('div.content_container');
					var paddingLeft = (contentContainer.css('paddingLeft')).slice(0,-2);
					var paddingRight = (contentContainer.css('paddingRight')).slice(0,-2);

					/* width of content column - width of image - 2px to account for border of quote block */ 
					var newTextWidth = parseInt(quoteBlock.width()) - parseInt(paddingLeft) - parseInt(paddingRight) - parseInt(imageWidth) - 2;
					$(this).width(newTextWidth);
				});				
			}
		};
	}();


function addPdfTrackEvent() {
	$("a[href*='pdf']").each(function(i){
		var file = $(this).attr("href");
	    $(this).click(function(){
	   	pageTracker._trackEvent("Downloads", "PDF", file); 
	    	cmCreatePageElementTag(file , "UOPX: Download > PDF");
	    //	alert(file);
	    });
	});
}

// after page is loaded (including images), adjust the column height
$(window).load(function(){
    adjustColHeight();
});

// declar global Variables
var globalVar = {
    siteWidth: 920,
    footerPadding: 10,
    leftNavSelClass: "selected",
    flashVersion: "9.0.0",
    videoWidth: "500",
    videoHeight: "340",
    commentsCharLimit: 2000
}

var isLogin = false;

// Mouse over function for top navigation  on IE browsers
var sfHover = function(navObj) {
    var sfEls = $(navObj);
	for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
            $(this).addClass("sfhover");
		}
		sfEls[i].onmouseleave=function() {
            $(this).removeClass("sfhover");
		}
	}
}

var applyCSSStyle = function(){
    // created round corner   

	$('div.modulePromo').corner({
		tl: {radius: 6},
		tr: {radius: 6},
		bl: {radius: 1},
		br: {radius: 1},
		antiAlias: true,
		autoPad: true	
	});			

	$('.quoteBlock').corner({
		tl: {radius: 20},
		tr: {radius: 20},
		bl: {radius: 20},
		br: {radius: 20},
		antiAlias: true,
		autoPad: true	
	});				

    // if IE, load the script for top navigation
    if($.browser.msie){
        sfHover("#topnav li");
        sfHover(".utilNav li");
        sfHover ("#loginNav li");
        sfHover (".rfi li");
        sfHover (".moduleFinder li");
        sfHover (".rfiDetails li");
        if(parseInt($.browser.version) < 7){
            // fix image flicker in ie6 or older
            try {
              document.execCommand("BackgroundImageCache", false, true);
            } catch(err) {}
        }
    }
    // if safari 2.x, no round corner on tool tip for safari 2.x
    if(!(jQuery.browser.safari && jQuery.browser.version < 500)){
    	
		$('div.tooltip div.roundedCorner').corner({
			tl: {radius: 6},
			tr: {radius: 6},
			bl: {radius: 6},
			br: {radius: 6},
			antiAlias: true,
			autoPad: true	
		});				
    }
       
    changeHomeBground();
    COMMON_table.stripeRows();
    $("ul#topnav li:last-child").attr("id","endTab");
	if ($('div.image + div.social_links').length) {
		$('div.social_links').css({'float': 'right'});
	}
}



// add padding to footer a tag
var adjustFooterWidth = function(){
    /* IE 6 needs a width for the li in order to float properly */
    var fCounter = $(".footerWrapper .bottomnavigation > ul > li").length;
    var listWidth = parseInt(globalVar.siteWidth/fCounter);
    $(".footerWrapper .bottomnavigation > ul > li").each(function(i){
        $(this).css("width", listWidth);    
    })
}

// adjust the promo column height to be the same as the contentWrapper height
var adjustColHeight = function(){
	/*
	 * if the print logo is hidden, ie, we're viewing on the web, do the column resize
	 */
	if ($('img.print').css('display') === 'none') {
    var contentHeight = $(".mainContent").height();
    var riteHeight = $(".ritePromoCol").height();
    if(riteHeight < contentHeight)
        $(".ritePromoCol").height(contentHeight);
	}
}

/*
var buildVideoLinks = function(){
    $(".videoWrapper button").each(function(i){
        var vUrl = $(this).attr("rel");
        if(vUrl != ""){
            $(this).click(function(){
                openVideoModal(vUrl);
            });
        }
    });
}
*/
// VIDEO CAROUSEL - NOT IN USE
/*
var buildVideoCarousel = function(){
    var videoList = $(".videoWrapper");
    $(".videoWrapper").each(function(i){
        buildVideoNav($(this));
    })
    // if there is more than one video
}

var buildVideoNav = function(vObj){
    // build the nav and high elelment
    var vParent;
    var navHtml = "";
    var vList = $("li", vObj);

    if(vList.length > 1){
        navHtml = "<div class='nav'>";

        for(var i= (vList.length - 1); i >= 0; i --){
            var title = $("h3", vList[i]).html();
            // add onclick event
            var vLink = $(".vLink", vList[i]);
            var vUrl = $(vLink).attr("rel");
            if(vUrl != ""){
                vLink.click(function(){
                    openVideoModal(vUrl);
                });    
            }
            navHtml += "<a href='javascript:void(0);' title='" + title + "'" + ((i==0)?"class='selected'":"") + " onclick='displayVideo(" + i + ", this)'" + "><span>" + title + "</span></a>";
            if(i > 0) $(vList[i]).hide();
        }
        navHtml += "</div>";
        $("ul", vObj).before(navHtml);
    }
}

var displayVideo = function (videoIndex, aLink){
    // get the parent
    var vList = $(aLink).parent().parent().find("li");
    var aList = $(aLink).parent().find("a");
    var aLen = aList.length;
    var aIndex;

    for(var i =0; i < vList.length; i++){
        aIndex = aLen - i - 1;
        if(videoIndex == i){
            $(aList[aIndex]).addClass("selected");
            $(vList[i]).show();
        } else {
            $(aList[aIndex]).removeClass("selected");
            $(vList[i]).hide();
        }
    }

}

var openVideoModal = function (url){
    var vDiv = $("#videoModal");
    if(vDiv.length < 1){
        $("body").append('<div id="videoModal"></div>');
    } else {
        $("#videoModal").html("");
    }

    var so = new SWFObject(url,"video",globalVar.videoWidth,globalVar.videoHeight,"9","#FFF");
	so.addParam("allowScriptAccess", "always");
	so.addParam("allowFullScreen","false");
	so.write("videoModal");


    //var params = {allowScriptAccess: "always", allowFullScreen: "false"};
   // swfobject.embedSWF(url, "video1", globalVar.videoWidth, globalVar.videoHeight, globalVar.flashVersion, null, null, params);

    $('#videoModal').modal({overlayId: "videomodal-overlay", containerId:"videomodal-container", onClose: closeVideoModal});

}


var closeVideoModal = function (dialog) {
    $.modal.close();
    $("#videoModal").html("");
}
*/
var buildAccordion = function(){
    if($('.accordion').length){
        $('.accordion').accordion({active: 1, header: 'h3', selectedClass: "selected", clearStyle: true, autoHeight: false});
        // add onclick for rss link
        $('.accordion a.rss').each(function(i){
            $(this).click(function(){
                var url = $(this).attr("href");
                window.open(url);
            });
        });
    }
}

// remove field text if not change
var addFieldOnOffEvent = function(){
    $(".fieldWrapper input").each(function(i){
        var defaultTxt = $(this).val();
        $(this).focus(function(){
            if(defaultTxt == $(this).val())
                $(this).val("");
        })
        $(this).blur(function(){
            if($(this).val() == "")
                $(this).val(defaultTxt);
        });
    })
}

var createCharCounter = function(){
    /* field counter div must be placed next to the text area */
    $(".fieldCounter").each(function(){
        var countObj = $(this).next(".counter").find("span");
        //var spanObj = $("span", countObj);
        $(this).textlimit(countObj,globalVar.commentsCharLimit);
    });
}


var changeHomeBground = function(){
    // if home page has alert, update the background image
    if($("#homepage").length){
        if($("#alert").length){
            $("#homepage").removeClass("homepage");
            $("#homepage").addClass("homepageAlert");
        }
    }
}

/* build content slider function */
var handleContentSlider = function(){
    // slider
    $('.contentSlider').each(function(){
        // hide the point if it is safari 2.x
        if(jQuery.browser.safari && jQuery.browser.version < 500){
            $(this).parent().find('.point').css('display', 'none');
        }
        var height = calculateSliderHeight($(this)) + "px";
        $(this).innerfade({
            speed: 2000,
            timeout: 15000,
            type: 'sequence',
            containerheight: height,
            children: 'p'
        });

    });
}

var calculateSliderHeight = function(sliderObj) {
    var height = 0;

    $('p', sliderObj).each(function(i){
        var width = $(this).width() + "px";
        $(this).css("width",width);
        if($(this).height() > height)
            height = $(this).height();
    });
    return height + 20;
}

var changeSocialLinksPos = function(){
	var element = $(".sociallinks");
	$(".sociallinks").remove();
	$(".pagetitle").after(element);
	
	var element2 = element.find(".utilNav");
	element2.removeClass("utilNav");
	element2.addClass("utilNavNoImg");
}


function showHideScholarship(ID){
    if(document.getElementById(ID).style.display == "none"){
        document.getElementById(ID).style.display = "block"
    }else if(document.getElementById(ID).style.display == "block"){
        document.getElementById(ID).style.display = "none"
    }

    var clsName ="";
    if(document.getElementById(ID + "li")!=null)
        clsName = document.getElementById(ID + "li").className;


    if(clsName=='plus')
        document.getElementById(ID + "li").className = 'minus';
    else if(clsName=='minus')
        document.getElementById(ID + "li").className = 'plus';
}

function ie6MouseoverEvent() {
    $(".ro").hover(
            function () {
              var elm = $(this).parent().find(".tooltipInfo");
              elm.addClass("tooltipInfoIe6");
              elm.removeClass("tooltipInfo");
            }, 
            function () {
                var elm = $(this).parent().find(".tooltipInfoIe6");
                elm.removeClass("tooltipInfoIe6");
                elm.addClass("tooltipInfo");
            }
    );  
}

var ImgRollover = {
   init: function()
   {
      this.preload();

      $(".ro").hover(
         function () { $(this).attr( 'src', ImgRollover.newimage($(this).attr('src')) );},
         function () { $(this).attr( 'src', ImgRollover.oldimage($(this).attr('src')) );}
      );
   },

   preload: function()
   {
      $(window).bind('load', function() {
         $('.ro').each( function( key, elm ) { $('<img>').attr( 'src', ImgRollover.newimage( $(this).attr('src') ) ); });
      });
   },

   newimage: function( src )
   {
      return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_on' + src.match(/(\.[a-z]+)$/)[0];
   },

   oldimage: function( src )
   {
      return src.replace(/_on\./, '.');

   }
};	
	
// Begin Aptimus

// Cookie code
// To get a cookie value by name use function:
// returnPopulatedValue(cookieName,attributeName);
// @returns query string and if none the value from the specified cookie (if avialable)
// Note cookie functions other than set and get are expecting name = value pairs and are "&" delimited

var theCookieName = "rf_prepop";
function setCookie(cookieName,cookieValue,expires,path,domain,secure)
{
  if (!domain) {
		var thisLocation = window.location.host;
		var thisHost = thisLocation.substring(thisLocation.indexOf("://") + 3);
		if (thisHost.indexOf(".") != thisHost.lastIndexOf(".")) {
			var domain = thisHost.substring(thisHost.indexOf("."));
		}
  }
  if (!path) {
  	var path = "/";
  }
  var curCookie = cookieName + "=" + escape(cookieValue) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}
function getCookie(cookieName)
{
  var dc = document.cookie;
  var prefix = cookieName + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1)
  {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  }
  else begin += 2;

  var end = dc.indexOf(";", begin);
  if (end == -1) end = dc.length;

  var returnVal = unescape( dc.substring( begin + prefix.length, end ) );
  return returnVal;
}
function deleteCookie(cookieName, path, domain)
{
  var now = new Date();
  fixDate( now ); // fix the bug in Navigator 2.0, Macintosh
  var expired = new Date(now.getTime() - 28 * 24 * 60 * 60 * 1000); // 28 days ago

  if ( getCookie( cookieName ) )
  {
    document.cookie = cookieName + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=" + expired.toGMTString();
  }
}
function fixDate(date)
{
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0) date.setTime(date.getTime() - skew);
}

function returnUrlAttributeValue(attributeName) {
  var pageURL = document.location.href;
  if (pageURL.indexOf('?') != -1) {
    var queryString = pageURL.substring(pageURL.indexOf('?') + 1,pageURL.length);
    var queryStringArray = queryString.split("&");
    for ( var i=0, v=queryStringArray.length; i<v; i++) {
      curItem = queryStringArray[i];
      if (curItem.substring(0,curItem.indexOf("=")).toLowerCase() == attributeName.toLowerCase()) {
        return curItem.substring(curItem.indexOf("=") + 1,curItem.length);
        break;
      }
    }
    return "";
  } else {
    return "";
  }
}
function returnCookieAttributeValue(cookieName,attributeName) {
  var cookieValue = getCookie(cookieName);
  var cookieValueArray = ( cookieValue ) ? cookieValue.split("&") : "";
  for (var i=0, v=cookieValueArray.length; i<v; i++) {
    curItem = cookieValueArray[i];
    if (curItem.substring(0,curItem.indexOf("=")).toLowerCase() == attributeName.toLowerCase()) {
      return curItem.substring(curItem.indexOf("=") + 1,curItem.length);
      break;
    }
  }
  return "";
}
function setCookieValue(cookieName,nameValuePair) {
  var thisCookie = getCookie(cookieName);
  var thisDelimiter = (thisCookie) ? "&" : "";
  if ( thisCookie != null ) {
    var thisName = nameValuePair.substring(0,nameValuePair.indexOf("="));
    if (thisCookie.indexOf(thisName) == -1) {
      setCookie(cookieName,thisCookie + thisDelimiter + nameValuePair,'','/');
    } else {
	  var arrCookiePairs = thisCookie.split("&");
	  if ( arrCookiePairs.length > 0 ) {
		  var strNameToMatch = nameValuePair.split("=")[0];
		  var strNewValue = nameValuePair.split("=")[1];
		  var strNewCookie = "";
		  if ( strNewValue != "" ) {
				for (var i=0, j=arrCookiePairs.length; i<j; i++) {
					if ( arrCookiePairs[i].split("=").length > 1 ) {
						var strCurName = arrCookiePairs[i].split("=")[0];
						if ( strCurName == strNameToMatch ) {
							strNewCookie = strNewCookie + strCurName + "=" + strNewValue;
						} else {
							strNewCookie = strNewCookie + arrCookiePairs[i];
						}
						if (i+1 != j) strNewCookie = strNewCookie + "&";
					}
				}
			}
	  }
	  if ( strNewCookie != "" ) {
      	setCookie(cookieName,strNewCookie,'','/');
      }
    }
  }
  else {
    setCookie(cookieName,nameValuePair,'','/');
  }
}
function returnPopulatedValue(cookieName,attributeName,defaultValue) {
  var urlAttributeValue = returnUrlAttributeValue(attributeName);
  if (urlAttributeValue != "") {
    // Get Value From URL
    // Phone Check
    if (attributeName == "CLPhone" && !returnSimplePhoneCheck(urlAttributeValue)) {
      return defaultValue;
    }
    return urlAttributeValue;
  } else {
    // Get Value From Cookie
    strCookieVal = returnCookieAttributeValue(cookieName,attributeName);
    if (strCookieVal == "" && defaultValue) {
      return defaultValue;
    } else {
      return strCookieVal;
    }
  }
}
function returnSimplePhoneCheck(phoneNumber) {
  var phoneRegex0 = /^\d\d\d\.\d\d\d\.\d\d\d\d$/;
  var phoneRegex1 = /^\d\d\d\-\d\d\d\-\d\d\d\d$/;
  var phoneRegex2 = /^\d-\d\d\d\-\d\d\d\-\d\d\d\d$/;
  if (phoneNumber.match(phoneRegex0) || phoneNumber.match(phoneRegex1) || phoneNumber.match(phoneRegex2)) {
    return true;
  } else {
    return false;
  }
}
function addQueryParamsToCookie(cookieName) {
  var pageURL = document.location.href;
  if (pageURL.indexOf('?') != -1) {
    var queryString = pageURL.substring(pageURL.indexOf('?') + 1,pageURL.length);
    var queryStringArray = queryString.split("&");
    for ( var i=0, v=queryStringArray.length; i<v; i++) {
      curItem = queryStringArray[i];
      setCookieValue(cookieName,curItem);
    }
  }
}
function cookieArgSpooler(cookieName,args) {
  var arrArgs = args.split(",");
  for (var i=0, n=arrArgs.length; i<n; i++) {
    thisValue = returnUrlAttributeValue(arrArgs[i]);
    if (thisValue == "" && arrArgs[i].indexOf("=") != -1) {
      thisValue = arrArgs[i].substring(arrArgs[i].indexOf("=") + 1, arrArgs[i].length);
    }
    if (returnUrlAttributeValue(arrArgs[i]) != "") {
      setCookieValue(cookieName,arrArgs[i] + "=" + thisValue);
    }
  }
}
function replaceInnerHTML(objId,newHTML,intChild) {
  if (newHTML != "") {
    var thisObj = document.getElementById(objId);
    if (thisObj) {
      if (intChild) {
        thisChildObj = thisObj.childNodes[intChild - 1]; // zero based index
        if (thisChildObj) {
          thisChildObj.innerHTML = newHTML;
        }
      }
      else {
        thisObj.innerHTML = newHTML;
      }
    }
  }
}
function popup(strUrl, iWidth, iHeight, iLeft, iTop, blnCenter, strName, strScroll, strMenus, strTools, strResize, strLocate)
{
  if ( blnCenter )
  {
    iLeft = (screen.width - iWidth) / 2;
    iTop = (screen.height - iHeight) / 2;
  }
  
  var winprops =  "location=" + strLocate + ",scrollbars=" + strScroll + ",menubar=" + strMenus + ",toolbar=" + strTools + ",resizable=" + strResize + ",left=" + iLeft + ",top=" + iTop + ",width=" + iWidth + ",height=" + iHeight;   

  var popup = window.open(strUrl,strName,winprops);
  popup.focus();
}

var _XHR_MS = false;

function createXHR()
{ 
  var request = false;
  try
  {
    request = new ActiveXObject('Msxml2.XMLHTTP');
    _XHR_MS = true;
  }
  catch (err2)
  {
    try
    {
      request = new ActiveXObject('Microsoft.XMLHTTP');

      _XHR_MS = true;
    }
    catch (err3)
    {
      try
      {
        request = new XMLHttpRequest();
        _XHR_MS = false;
      }
      catch (err1)
      {
        request = false;
      }
    }
  }
  return request;
}

function isXHR_MS()
{
  return _XHR_MS;
}

function startWorkflowUsingPath(strWorkflowName, strPayloadPath)
{
  var strModel = "/etc/workflow/models/" + strWorkflowName;
  var strUrl = "/etc/workflow/instances";
  var xhr = createXHR();

  var strPath = strPayloadPath;
  var idx = strPayloadPath.lastIndexOf('.');

  if (idx > 0)
    strPath = strPayloadPath.substring(0, idx);

  var params = "model=" + strModel + "&payloadType=JCR_PATH&payload=" + strPath;
  xhr.open("POST", strUrl, true);

  //Send the proper header information along with the request
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.setRequestHeader("Content-length", params.length);
  xhr.setRequestHeader("Connection", "close");

  xhr.onreadystatechange = function() 
  {
    //Call a function when the state changes.
    if(xhr.readyState == 4) 
    {
      //alert("Workflow started");
    }
  }
  xhr.send(params);
}

function startWorkflow(strWorkflowName)
{
  startWorkflowUsingPath(strWorkflowName, location.pathname);
}
