/**
 * common jquery functions - needs to be included in the site templates after the jquery includes
 */
$(document).ready(function(){								 
	//initFormFocus(); // SM 10Nov09: Disabled
	initArbSearch();
	
	// SM 18Nov08: If you select a textfield, select all text if it's the default value
	// Handy for search forms etc...
	$("input, textarea").focus(function(){
    // only select if the text has not changed
    //if(this.value == this.defaultValue) { this.select(); }
    if(this.value == this.defaultValue) { $(this).select(); }
  });
  
  // SM 09Jun11: Fix z-index issues for IE7
  zIndexFix();
  
  // SM 14Jun11: Auto-scroll page to top (handy for linking to tabs with anchors)
  if($.query.get('scrollTop')) { scrollPageToTop(); }
  
  // SM 20Jul11: As per KH's request, inject classes into li's
  $('ul').each(function(){
    $(this).children('li:first').addClass('first');
    $(this).children('li:last').addClass('last');
  });
    
});

/**
 * Generic method to set the input focus to the first element on any page.
 */
function initFormFocus() {
  // SM 20Aug07: Try setting the cursor focus on the first element of any form.
  //$(":input:first").focus();
	$(":text:first").focus().select();
	//$("input[name='frm_uname']").focus();	
}

/**
 * Setup the hide/show behaviour for arbsearch pages. Needs jquery cookie plugin.
 */
function initArbSearch() {
  
  if(0 == $('.srch_table').length) { return false; }
  
	// arbsearch hideshow toggle function
	// todo: use a cookie to remember state between paginations
	$('.arbsearch_hideshow').css({cursor: 'pointer'});
	//$('.srch_table').css('margin', '10px 0px 10px 20px');
	
	var img_toggle_hide = "http://images.regional.org.au/shared/images/as_toggle_hide.gif";
	var img_toggle_show = "http://images.regional.org.au/shared/images/as_toggle_show.gif";
	
	var as_toggle_hide = function() {
			$.cookie('arbsearch_toggle', 'hide'); // get cookie
			//$('.srch_table').slideUp();
			$('.srch_table').hide();
			//$(this).html('show');
			$(this).attr('src', img_toggle_show);
	};
	var as_toggle_show = function() {
			$.cookie('arbsearch_toggle', 'show'); // get cookie
			//$('.srch_table').slideDown();
			$('.srch_table').show();
			//$(this).html('hide');
			$(this).attr('src', img_toggle_hide);
	};
	
	// Now bind these functions in the correct order when the page loads.
	var initial_state = $.cookie('arbsearch_toggle') ? $.cookie('arbsearch_toggle') : 'show';
	switch(initial_state) {
		case 'hide':
			$('.srch_table').hide();
			//$('.arbsearch_hideshow').html('show');
			$('.arbsearch_hideshow').attr('src', img_toggle_show);
			$('.arbsearch_hideshow').toggle(as_toggle_show,as_toggle_hide);		
			break;
		case 'show':
			$('.srch_table').show();
			//$('.arbsearch_hideshow').html('hide');
			$('.arbsearch_hideshow').attr('src', img_toggle_hide);
			$('.arbsearch_hideshow').toggle(as_toggle_hide, as_toggle_show);
			break;
	}	
}

/**
 * SM 20/05/2010 12:21:00 PM
 * Send ajax command to server to set flag
 * Hide display now
 */
function hideNewSiteMsg(elem) {
  $.get('/my/admin/ajax', { action: 'new_site_msg_hide' }); // send command to server to remember for this session
  $(elem).parents('div.flash_message:first').fadeOut('slow', function() { $(this).remove() });
}


/*
  SM 10Mar11: See http://ejohn.org/blog/title-capitalization-in-javascript/

  JavaScript port of John Gruber's TitleCase Perl script:
  http://daringfireball.net/projects/titlecase/TitleCase.pl

  This filter changes all words to Title Caps, and attempts to be clever
  about *un*capitalizing small words like a/an/the in the input.

  The list of "small words" which are not capped comes from
  the New York Times Manual of Style, plus 'vs' and 'v'.

  License: http://www.opensource.org/licenses/mit-license.php

  David Lindquist (http://www.stringify.com/)
  21 May 2008
*/

String.prototype.toTitleCase = function() {
    var small_words = 'a an and as at but by en for if in of on or the to v[.]? via vs[.]?'.split(/\s/);
    var punct = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
    var small_re = small_words.join('|');

    function capitalize(s) {
        return s.charAt(0).toUpperCase() + s.substring(1);
    }

    var general_repl = [
        [/\b([A-Za-z][a-z.\']*)\b/g,
         function(str, word) {
             if (/[A-Za-z][.][A-Za-z]/.test(word))
                 return word;
             return capitalize(word);
         }
        ],
        [new RegExp('\\b(' + small_re + ')\\b', 'ig'),
         function(str, small) { return small.toLowerCase(); }
        ],
        [new RegExp('^([' + punct + ']*)(' + small_re + ')\\b', 'ig'),
         function(str, punct, small) { return punct + capitalize(small); }
        ],
        [new RegExp('\\b(' + small_re + ')([' + punct + ']*)$', 'ig'),
         function(str, small, punct) { return capitalize(small) + punct; }
        ]
    ];

    var special_repl = [
        [/ V(s?)\. /g,
         function(str, s) { return ' v' + s + '. '; }
        ],
        [/([\'\u2019])S\b/g,
         function(str, apos) { return apos + 's' }
        ],
        [/\b(AT&T|Q&A)\b/ig,
         function(str, s) { return s.toUpperCase(); }
        ]
    ];

    var split_re = /([:.;?!][ ]|(?:[ ]|^)[\"\u201c])/g;
    var tokens_in = []
    var tokens_out = [];
    var token, regex, repl, idx = 0, m;

    while ((m = split_re.exec(this)) != null) {
        tokens_in.push(this.substring(idx, m.index), m[1]);
        idx = split_re.lastIndex;
    }
    tokens_in.push(this.substring(idx));

    for (var i = 0; i < tokens_in.length; i++) {
        token = tokens_in[i];
        for (var j = 0; j < general_repl.length; j++) {
            regex = general_repl[j][0];
            repl  = general_repl[j][1];
            token = token.replace(regex, repl);
        }
        tokens_out.push(token);
    }
    var title = tokens_out.join('');
    for (var k = 0; k < special_repl.length; k++) {
        regex = special_repl[k][0];
        repl  = special_repl[k][1];
        title = title.replace(regex, repl);
    }

    return title;
}


/**
 * Quick function to restripe the file list after a delete
 * SM 31Mar11: Moved from Editor2's tree.js to here.
 */
function restripeTable(class_name) {
  // Zebra striping
  $("."+class_name+" > tbody > tr:even").removeClass('odd').addClass('even');
  $("."+class_name+" > tbody > tr:odd").removeClass('even').addClass('odd');
}


/**
 * SM 09Jun11: z-index fix
 * See http://brenelz.com/blog/squish-the-internet-explorer-z-index-bug/
 * http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/
 * SM 20Jun11: Skip certain divs (for quick site debugging) or bypass completely
 */
function zIndexFix() {
  //if('1' == $.query.get('no-zindex-fix')) { return; }
  if(!$.browser.msie) { return; }
  if(parseInt($.browser.version) > 7) { return; }
  
  // Grabbed from http://richa.avasthi.name/blogs/tepumpkin/2008/01/11/ie7-lessons-learned/
  $("div.megamenu_body").parents().each(function() {
    var p = $(this);
    var pos = p.css("position");
  
    // If it's positioned,
    if(pos == "relative" || pos == "absolute" || pos == "fixed") {
      p.hover(function() {
        $(this).css('z-index', 10000);
      }, function() {
        $(this).css('z-index', '');
      });
    }
  });
  
  /*
  // HACK Bypass for wob
  if(-1 != window.location.hostname.indexOf('womenonboards')) { return; }
  
  var zIndexNumber = 1000;
  $('div').each(function() {
    if($(this).hasClass('no-zindex-fix')) { return true; }
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
  });
  */
}

/**
 * SM 14Jun11: Allow a page to be scrolled to the top
 */
function scrollPageToTop() {
  $('html, body').animate({scrollTop:0}, 'slow');
}

