/*
	Common JS functions shared by many pages
*/

var common_popup_features_default = 'width=800,height=600,resizable=yes,scrollbars=yes';

/** 
 *
 */
function popup(url,name,features,template){
	
	// SM 29Jul10: New feature
	if(template) {
		switch(template) {
			case 'wide':
				name 		 = 'PopupWindowWide';
				features = 'width=960,height=500,resizable=yes,scrollbars=yes';
				break;
      case 'print_friendly':
        name 		 = 'PopupWindowPrintFriendly';
        features = 'width=640,height=480,resizable=yes,scrollbars=yes,menubar=yes';
        break;				
		}
	}
	
	name = typeof(name) != 'undefined' ? name : 'PopupWindow';
	features = typeof(features) != 'undefined' ? features : common_popup_features_default;
	
	newwindow=window.open(url, name, features);
	if (window.focus) {newwindow.focus()}
	
	//return false;
	//return newwindow;
}

// SM 17Aug09: For all popups to use.
function popup_close() {
  var isThickbox = $.query.get('keepThis');
  if(isThickbox && (typeof self.parent.tb_remove == 'function')) { 
    self.parent.tb_remove(); 
  } else {
    window.close();
  }
}

/**
 * OOP principle - make a copy of an object so you don't mess with the original's values.
 */
function clone(myObj) {
	if(typeof(myObj) != 'object') return myObj;
	if(myObj == null) return myObj;

	var myNewObj = new Object();

	for(var i in myObj)
		myNewObj[i] = clone(myObj[i]);

	return myNewObj;
}

/**
 * Handy for any "delete" action that requires a confirm.
 */
function confirmDelete(msg) {
	if(!msg) { msg = 'delete this entry'; }
	return confirmAction(msg);
}

/**
 * More generic helper function.
 */
function confirmAction(msg) {
	if(!msg) { msg = 'proceed'; }
	return confirm("Are you sure you wish to "+msg+"?") ? true : false;
}

/**
 * String function - trim whitespaces, leading/trailing.
 * SM 20May09: Note $.trim() jQuery function also available.
 */
function common_trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 

/* SM 31Mar08: Add trim() function to javascript in general. */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

/* SM 14/01/2010 10:10:32 AM: Addding a HTML strip function to String */
String.prototype.stripHTML = function () {
  var reTag = /<(?:.|\s)*?>/g;
  return this.replace(reTag, "");
};

/* SM 29/01/2010 3:14:57 PM: String replaceAll function */
String.prototype.replaceAll = function(from, to) {
  return this.replace(new RegExp(from, 'g'),to);
}

/**
 * Parse a querystring and return the base url, eg
 * http://foo.bar#blah -> http://foo.bar
 * http://foo.bar?a=b	-> http://foo.bar
 */
function common_getBaseUrl(url) {
	
	url = typeof(url) != 'undefined' ? url : window.location.href;
	
	if(url.indexOf('?') > 0) {
		url = url.substring(0, url.indexOf('?'));
	} else if(url.indexOf('#') > 0) {
		url = url.substring(0, url.indexOf('#'));
	}
	return url;
}

/**
 * Given a string, find the code in <script> tags and run using execScript
 * IE functionality only really.
 */
function evalScripts(responseText) {
	// Only need to attempt this with IE.
	if (window.execScript) {
		scripts = [];
		var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
		while ((script = regexp.exec(responseText))) scripts.push(script[1]);
		scripts = scripts.join('\n');
		if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);
	}
}

/**
 * Remotely load a css file into the browser.
 */
function load_css(path) {
	path = 'http://dev.regional.org.au' + path; // debug
	if(document.createStyleSheet) {
		document.createStyleSheet(path);
	} else {
		var styles = "@import url('"+path+"');";
		var newSS=document.createElement('link');
		newSS.rel='stylesheet';
		newSS.href='data:text/css,'+escape(styles);
		document.getElementsByTagName("head")[0].appendChild(newSS);
	}
}

/**
 * Quick hack to determine in JS if we're inside the scope interface.
 * todo: Implement something more robust.
 */
function is_scope_interface() {
	return (location.href.indexOf('/scope') > 0);
}

/**
* More generic effort at creating a wordcounter setup to be bound anywhere.
* wcSourceField, wcDestField are jquery references to an element, 
* eg $(":input[name='objectives']") & $('#wordcount')
*/
function tri_initWordCounter(wcSourceField, wcDestField, maxWords) {
	// Set wordcounter params
	var wc_old_css          = wcDestField.css('color');
	var wc_old_border_color = wcSourceField.css('border-color');

	// Set default wordcount when opening the popup.
	wcDestField.html(tri_countWords(wcSourceField));

	// Bind the keypress event to re-count the words as the user types.
	// SM 07Jan10: Enhancements
	//wcSourceField.keyup(function(){
	wcSourceField.bind('keyup click blur focus change paste', function() {

		var count = tri_countWords($(this));
		wcDestField.html(count);
		//if(count >= maxWords) {
		if(count > maxWords) {
			// Exceeded the max - complain.
			wcDestField.css('color', 'red');
			wcSourceField.css('border-color', 'red');
		} else {
			// Back to normal
			wcDestField.css('color', wc_old_css);
			wcSourceField.css('border-color', wc_old_border_color);
		}
	});
} 

/**
* Generic wordcounting, give it a dom element.
* SM 24Aug09: Allow for empty strings to return 0 length.
*/
function tri_countWords(e) {
  var str = $(e).val();
  return tri_countWordsString(str);
}

function tri_countWordsString(str) {
  if(0 == $.trim(str).length) { return 0; } 
	//return str.split(/\b[\s,\.-:;]*/).length;
	//return $.trim(str).split(/[\s\.\?]+/).length;
	//return $.trim(str).replace(/\s+/g," ").split(' ').length;
	var count = $.trim(str).replace("\r\n"," ").replace(/[\s]+/," ").split(' ').length;
	//alert("wordcount:"+count);
	return count;
}

function reload_opener() {
	if (window.opener && !window.opener.closed) {
    window.opener.location.reload();
	} 
}

/**
 * SM 17Feb09: Aware of popups, thickbox, etc
 */
function reloadOpener_test() {
  if(opener) {
    opener.location.reload(true);
  } else if(self.parent) {
    // we're into thickbox territory now
    if(typeof self.parent.reloadPanel == 'function') { self.parent.reloadPanel(); return true; }
    else if(typeof self.parent.reloadTree == 'function') { self.parent.reloadTree(); return true; }
    else { self.parent.reload(true); return true; }
  } else {
    //alert('sorry, no opener found');
  }
}

/**
 * SM 06Nov09: Generic reload, tabs or no-tabs
 * Here in common js so it's available on any page.
 *
 * FIXME Static content tabs = window reload
 */
function tabSensitiveReload(elem) {
  
  // Check for non-tabs page
  if(0 == $('.ui-tabs').length) {
    //window.location.reload();  
    window.location.href = window.location.href;
    return true;
  }
  
  //alert('on tabs');
  
  var tab_panel = $(elem).parents("div.ui-tabs-panel:first");
  
  // Did this request originate from outside a tab? Eg did the page request a reload?
  if(0 == tab_panel.length) { 
    window.location.href = window.location.href; 
    return true;
  }
  
  // Ok we're tabs away, lets reload
  
  
  if(tab_panel.hasClass('ui-tabs-static')) {
    // static tab, reload page  
    window.location.href = window.location.href; 
    return true;
  } else {
    // remote/ajax tab, call load method
    var $tabs = $('.ui-tabs').tabs();
    var selected = $tabs.tabs('option', 'selected'); // => 0
    $tabs.tabs('load', selected);
  }

}

/**
 * SM 18/02/2010 1:58:06 PM: Handy function
 */
function get_file_extension(filename) {
  /*
  if( filename.length == 0 ) return ""; 
  var dot = filename.lastIndexOf("."); 
  if( dot == -1 ) return ""; 
  var extension = filename.substr(dot,filename.length); 
  return extension; 
  */
  return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}

/**
 * Wrapper for firebug console so non-FF browsers are ok?
 * SM 11Nov10: Moved to common.js
 */
function logMsg(msg) {
  return true; // comment out to enable
  if(typeof console != 'object') { return false; }
  console.log(msg); // SM 10Nov10: commented out after devwork done
}

/**
 * Spawn a popup to a printer-friendly implementation of this page
 */
function printFriendly() {
  popup($.query.set("print", 1).toString(), 'printFriendly', null, 'print_friendly');
}

/**
 * Helper function to determine if a keypress is a "user input key" - something
 * the user wants to search on, not a keypress like ctrl, shift
 * http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx 
 */
function tri_is_user_input_key(keyCode) {
  //console.log("keyCode:"+event.keyCode);
  var result = true;
  // enter = 13
  switch(keyCode) {
    case 17: // shift
    case 18: // alt 
    case 16: // ctrl
    case 20: // caps lock (SM: I use this for mumble push-to-talk)
    case 32: // space bar
    case 37: // arrow key
    case 38: // arrow key
    case 39: // arrow key
    case 40: // arrow key
      result = false;
      break;
  }
  return result;
}


/*
  SM 17Feb11: Setup faux console so IE doesn't spit the dummy
  Updates to add other APIs so I can use them in FF.
  http://getfirebug.com/wiki/index.php/Console_API
  
  Currently not in use - just turn off resource caching and debug with Firebug
*/
if('object' != typeof console) { 
  console = { 
    log   : function(){}, 
    debug : function(){}, 
    info  : function(){}, 
    warn  : function(){}, 
    error : function(){}
  }; 
}

/**
 * SM 01Sep11: Helper function for query parsing that's NOT reliant on window
 */
function common_get_param_by_name(name, search) {
  if('undefined' == typeof search) { search = window.location.search; }
  var match = RegExp('[?&]' + name + '=([^&]*)').exec(search);
  return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

