/* Cookie Functionality */

function getCookieVal(offset) {
  var endstr = document.cookie.indexOf (';', offset);
  if(endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
  var arg = name + '=';
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while(i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(' ', i) + 1;
    if (i == 0) break;
  }
  return null;
}

function createCookie(name, value) {
  var expires = new Date().getTime();
  expires += ((2419200 * 1000) * 1);
  expires = new Date(expires);
  document.cookie = name + '=' + value + '; path=/' + '; expires=' + expires.toGMTString();
}

function setCookie(name, value) {
  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;
  expires = new Date().getTime();
  expires += ((2419200 * 1000) * 1);
  expires = new Date(expires);
  document.cookie = name + '=' + value + ((expires == null) ? '' : ('; expires=' + expires.toGMTString())) + '; path=/' + ((domain == null) ? '' : ('; domain=' + domain)) +((secure == true) ? '; secure' : '');
}

/* Tags Functionality */

function showTag(p_tagId) {
  jQuery("#" + p_tagId).show();
}

function scheduleHideTag(p_tagId) {
  tagTimeout = window.setTimeout("hideTag('" + p_tagId + "');", 1500);
}

function abortHideTag () {
  if (window.tagTimeout) window.clearTimeout(tagTimeout);
}

function hideTag(p_tagId) {
  jQuery("#" + p_tagId).hide();
}

function addTag(tagValue, tagId, tagCookieName) {
  var mytags = document.getElementById('mytags');
  var tagcheck = document.getElementById('tag_' + tagId);
  if ((typeof(mytags) != 'undefined' && mytags != null) && (typeof(tagcheck) == 'undefined' || tagcheck == null)) {
    var tag = document.createElement('li');
    tag.id = 'tag_' + tagId;
    var l_url = location.href;
    l_url += (l_url.indexOf('?') >= 0 ? '&' : '?') + 'type=' + tagValue;     
    tag.innerHTML = '<a href="' + l_url + '">' + tagValue + '</a>' + '<a href="javascript:removeTag(\'' + tagId + '\', \'' + tagValue + '\', \'' + tagCookieName + '\');"><img src="/images/delete.gif" alt="Remove Tag"/></a>';
    mytags.appendChild(tag);
  }
  updateTagCookie(tagValue, 'update', tagCookieName);
}

function updateTagCookie(value, action, tagCookieName) {
  var l_cookieVal = getCookie(tagCookieName);
  if (action == 'update') {
    if (l_cookieVal != null) {
      l_cookieVal = l_cookieVal.replace(/"/g, '');
      if (l_cookieVal.indexOf(value) < 0) {
        if( l_cookieVal != '') l_cookieVal += '||' + value;
        else l_cookieVal = value;
      }
    }
    else if(l_cookieVal == null) l_cookieVal = value;
  }
  else {
    if (l_cookieVal != null && l_cookieVal.indexOf(value) >= 0) {
      var temp = new Array();
      var i = 0;
      l_cookieVal = l_cookieVal.replace(/"/g, '');
      temp = l_cookieVal.split('||');
      l_cookieVal = '';
      while (i < temp.length) {
        if (temp[i] != value) {
          if (l_cookieVal != '') l_cookieVal += '||' + temp[i];
          else l_cookieVal = temp[i];
        }
        i++;
      }
    }
  }
  l_cookieVal = '"' + l_cookieVal + '"';
  var l_cookie = getCookie(tagCookieName);
  if (l_cookie == null) createCookie(tagCookieName, l_cookieVal);
  else setCookie(tagCookieName, l_cookieVal);
}

function removeTag(tagId, tagValue, tagCookieName) {
  var tagToRemove = document.getElementById('tag_' + tagId);
  if (typeof(tagToRemove) != 'undefined') {
    tagToRemove.parentNode.removeChild(tagToRemove);
  }
  updateTagCookie(tagValue, 'delete', tagCookieName);
}

/* Form Functionality */

function submitConstructedForm(p_form) {
   document.body.appendChild(p_form);
   p_form.submit();
}

/* The purpose of this code is to dynamically generate forms
 * that can be used for submitting content to the web server.
 * NB: This dynamic form generation is not intended to be used
 * for user accessable forms, hence the reason for the forms
 * display style being set to none.
 */
function constructForm(p_form, p_elements) {
   var l_form;
   var l_element;
   var l_len;
   var l_name;
   var l_value;
   var l_tag;
   var l_type;
   var l_i;
   
   l_form = document.createElement('form');
   
   l_form.method = p_form.get('method');
   l_form.action = p_form.get('action');

   l_form.style.display = 'none';
   
   l_len = p_elements.length;   
   for (l_i = 0; l_i < l_len; l_i++) {
      l_name = p_elements[l_i][0];
      l_value = p_elements[l_i][1];
      l_tag = p_elements[l_i][2];
      l_type = p_elements[l_i][3];
      try {
         l_element = document.createElement('<' + l_tag + ' name="' + l_name + '"' + (l_type == null ? '' : ' type="' + l_type + '"') + '>');
      } catch (e) {
    	 l_element = document.createElement(l_tag);
    	 l_element.setAttribute('name', l_name);
    	 if (l_type != null) l_element.setAttribute('type', l_type);
      }
      if (l_element) {
         if (l_tag.toLowerCase() == 'textarea') {
            l_element.innerHTML = l_value;
         } else {
            l_element.setAttribute('value', l_value);
         }
      }
      l_form.appendChild(l_element);
   }
   
   return l_form;
}

/**
 * Checks for potential cross site scripting text.
 * 
 * @param p_str
 * @return
 */
function containsXSS(p_str) {
    var lower = p_str.toLowerCase();
    var l_containsXSS = false;
    if(lower.match(/<script/)
    		|| lower.match(/<\/script/)
    		|| lower.match(/javascript:/)
    		|| lower.match(/href=/)
    		|| lower.match(/<img/)
    		|| lower.match(/<object/) ) {
    	
    	l_containsXSS = true; 
	} 
    
    return l_containsXSS;
}

/**
 * Checks for potential XSS attack in element. 
 * Always returns false if element cant be found, or it doesnt have a 'value' attribute. 
 * 
 * @param p_elemName
 * @return
 */
function elementContainsXSS(p_elemName) {
	if ($(p_elemName)) {
		if ($(p_elemName).value) {
			return containsXSS($(p_elemName).value);
		}
	}
	return false;
}

function trimResult(p_str) {
  return jQuery.trim(p_str);
}

function toggleLayer(p_selector) {
  jQuery(p_selector).toggle();
}

function hideLayer(p_selector) {
  jQuery(p_selector).hide();
}

function showLayer(p_selector) {
  jQuery(p_selector).show();
}

function setHtml(p_selector, p_content) {
  jQuery(p_selector).html(p_content);
}

function setValue(p_selector, p_value) {
  jQuery(p_selector).val(p_value);
}

/* Load response straight into the DOM
 *
 * parameters:
 * p_elements - DOM elements to update
 * p_url - resource to request
 * 3rd parameter - JSON data to be sent in request (optional)
 * 4th parameter - function to call with response (optional)
 */
function ajaxLoadIntoPage(p_elements, p_url) {
  if (arguments.length == 2) {
    jQuery(p_elements).load(p_url);
  } else if (arguments.length == 3) {
    jQuery(p_elements).load(p_url, arguments[2]);
  } else if (arguments.length == 4) {
    jQuery(p_elements).load(p_url, arguments[2], arguments[3]);
  }
}

/* Perform a http request and return the reponse, optionally perform processing
 * 
 * parameters:
 * p_url - resource to request
 * p_extra - see http://docs.jquery.com/Ajax/jQuery.ajax#options
 *
 * The idea with this function is that at a later stage if a migration away from jQuery takes place we'll be better positioned.
 */
function ajaxRequest(p_url, p_extra) {
  var response;
  var request = p_extra;
  
  request.url = p_url;
  
  if (typeof(p_extra.async) == 'undefined' || p_extra.async) {
    jQuery.ajax(request);
  } else {
    response = jQuery.ajax(request);
    return response.responseText;
  }
}

function ajaxFormPost(p_formId, p_url, p_resultDivId) { 
	var fieldscontainXSS = false;
	jQuery("#" + p_formId).find("input").each(function(i){
	  if(containsXSS($(this).value)){
	  	fieldscontainXSS = true;
	  }
	}); 
	
	if(!fieldscontainXSS){
			jQuery.post(p_url, jQuery("#" + p_formId).serialize(), function(data,status){
					jQuery("#" + p_resultDivId).html(data);
			});  
	} else{
		alert('Could not post form');
	}
}

function displayLoadingIcon(p_resultDivId) {
  jQuery("#" + p_resultDivId).html("<p><img src='/images/loadinganimation_small.gif' alt='Loading...' border='0' /></p>");
}

function ajaxSearchPost(p_formId, p_resultDivId, p_webId, p_includeExistingQueryString) { 
  var l_url = '/public/search.jsp';
  var l_params = '';
  var l_fieldsContainXSS = false;
  
	jQuery("#" + p_formId).find("input").each(function(i){
	  if(containsXSS($(this).value)){
	  	l_fieldsContainXSS = true;
	  }
	}); 
	
	if(l_fieldsContainXSS){
		alert('Invalid Search');
	} else{

		displayLoadingIcon(p_resultDivId);

		if (p_includeExistingQueryString) {
			if (location.href.indexOf('?') > -1) {
				l_params = location.href.substring(location.href.indexOf('?') + 1);
			}
		}

		if (l_params.indexOf('f_abstract_enabled') < 0) {
			l_params += (l_params == '' ? '' : '&') +
            			'f_abstract_enabled=' + m_abstract_enabled + 
            			'&f_abstract_fragment_count=' + m_abstract_fragment_count + 
            			'&f_abstract_fragment_size=' + m_abstract_fragment_size + 
            			'&f_abstract_fragment_separator=' + m_abstract_fragment_separator;
		}

		l_params += (l_params == '' ? '' : '&') +
		            'f_web_id=' + p_webId;

		if (l_params != '') {
			l_url = l_url + '?' + l_params;
		}

		ajaxFormPost(p_formId, l_url, p_resultDivId);     
	}
}

function ajaxEditModeLinkPost(p_resultDivId) { 
  var l_url = '/public/editmodelink.jsp';
  var l_params = 'f_helpertext_in_edit_mode=' + m_editmodelink_helpertext_in_edit_mode + 
                 '&f_helpertext_in_normal_mode=' + m_editmodelink_helpertext_in_normal_mode + 
                 '&f_page_id=' + m_editmodelink_page_id +
                 '&f_web_id=' + m_editmodelink_web_id +
                 '&f_url=' + m_editmodelink_url_disp +
                 '&f_url_layout=' + m_editmodelink_url_edit;

  ajaxRequest(l_url, { data: l_params, cache: false,  success: function(html) { setHtml("#" + p_resultDivId, trimResult(html)); } });    
}

function ajaxEditModeLinkUpdate() { 
  var l_url = '/public/editmodelink.jsp';
  
  var l_params = 'f_action=change' +
                 '&f_page_id=' + m_editmodelink_page_id +
                 '&f_web_id=' + m_editmodelink_web_id +
                 '&f_url=' + m_editmodelink_url_disp +
                 '&f_url_layout=' + m_editmodelink_url_edit;
  
  ajaxRequest(l_url, { data: l_params, cache: false, success: function(html) { location.href = trimResult(html); } });
}

function ajaxShareAdd(p_url, p_resourceId, p_returnPageId, p_successMsg, p_failureMsg) {
  var l_params = '';

  if (p_url.indexOf('?') > -1) {
    l_params = p_url.substring(p_url.indexOf('?') + 1);
    p_url = p_url.substring(0, p_url.indexOf('?'));
  }

  l_params += (l_params == '' ? '' : '&') +
              'pid=' + p_resourceId +
              '&returnto=' + p_returnPageId;  
  
  ajaxRequest(p_url, { data: l_params, cache: false, success: function(html) { alert(p_successMsg); } });  
}

function ajaxListingPost(p_divId, p_thes) {
  setValue("#type", p_thes);
  document.filterForm.submit();
}



/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

//Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

//Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

//For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

function isValidEmailAddress(emailAddress) {  
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
  return pattern.test(emailAddress);  
} 