/*
ID: basic
Name: Common
Version: 1.0
Description: Commonly used javascript functions.
Dependents: jQuery
*/

// Similar Posts Drops
var cats = function() {
	$( '.category' ).click( function() {
		$( this ).toggleClass( 'active' )
		$( this ).siblings( '.dropdown' ).toggle();
		$( this ).find( '.indicator' ).toggleClass( 'indicator-active' );
		return false;
	} );
	}
$(document).ready(cats);


// Subnav Drops
var subnav = function() {
	$( '#navigation ul li' ).bind( "mouseover", function() {
		$( this ).children( '.drops' ).show();
		$( this ).addClass( 'hover-active' );
	}).bind( "mouseout", function() {		
		$( this ).children( '.drops' ).hide();
		$( this ).removeClass( 'hover-active' );
	} );
	}
$(document).ready(subnav);

// Deactive Dummy "#" Links
var linkBreaker = function() { $('a[@href=#]').click( function(){ return false; } ); }
//	$(document).ready(linkBreaker);


// Set Outbound Links by Class Name
var outLinks = function() { $('a.out').click( function(){ this.target = '_blank'; } ); }
$(document).ready(outLinks);


// Pop-up Windows by Size
jQuery.fn.popwindow = function() {
	return this.each(
		function(){
			var dimensions = this.className.match(/[0-9]{1,4}x[0-9]{1,4}/) + '';
			var width = eval(dimensions.split('x')[0]), height = eval(dimensions.split('x')[1]);
			$(this).bind('click',function() { window.open("" + this.href + "",null,'width=' + width + ', height=' + height); return false; })
		}
	)
}
//var popWindows = function() { $('a.popup').popwindow(); }
//$(document).ready(popWindows);

// Search form
var sitesearch = {
	init : function()
	{
		var keyword = $('#top-keyword'), def = keyword.val();
		keyword.focus( function(){
			var value = $(this).val() == def ? '' : $(this).val();
			$(this).val(value);
		});
		keyword.blur( function() {
			var value = $(this).val() == '' ? def : $(this).val();
			$(this).val(value);
		});
	}
}
$(document).ready(sitesearch.init);


// Correct PNG Images for IE 6
var pngFix = {
	init : function() {
		var imgs = $("img[@src*=png]");
		imgs.each(
			function() {
				var newSrc = $(this).attr('src'), newID = $(this).attr('id'), newClass = $(this).attr('class'), newTitle = $(this).attr('alt'), newStyle = $(this).attr('style'), newAlign = $(this).attr('align'), newW = $(this).attr('width'), newH = $(this).attr('height'), dfilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src='"+ newSrc +"',sizingMethod=image)";
				
				var span = document.createElement('span');
				$(span).attr({ 'id':newID, 'class':newClass, 'title':newTitle, 'style':newStyle });
				$(span).css({'display':'inline-block', 'background':'none', width:newW+'px', height:newH+'px', filter:dfilter});
				if( newAlign ) $(span).css({'float':newAlign});
				if( $(this).parent('a') ) $(span).css({'cursor':'hand'});
				$(this).after(span).remove();
			}
		)
	}
}
if( $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent) )
	$(document).ready(pngFix.init);


// Image Rollovers
var rollovers = function(){ $('img.rollover').rollover(); }
jQuery.fn.rollover = function() {
	return this.each(
		function() {
			var srcString = this.src;
			var ext = srcString.substring(srcString.length - 4, srcString.length), name = srcString.substring(0, srcString.length - 4), overImage = name + '_over' + ext;
			var img = new Image();	img.src = overImage;
			$(this).bind('mouseover',function(){ this.src = overImage; } );
			$(this).bind('mouseout',function(){ this.src = srcString; } );
		}
	)
}
$(document).ready(rollovers);

	
// IE Image Rollovers
var IEroll = {
	init : function() {
		$("span.rollover").hover( IEroll.over, IEroll.out );
	},
	over : function() {
		var geturl = new RegExp(/src='([^ ]+)'/i);
		var filter = this.style.filter, src = geturl.exec(filter)[1];
		var ext = src.substring(src.length - 4, src.length), name = src.substring(0, src.length - 4), newSrc = name +'_over'+ ext;
		var image = new Image();
		image.src = newSrc;
		var dfilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + newSrc + "\', sizingMethod='image')";
		$(this).css({filter:dfilter});
	},
	out : function() {
		var geturl = new RegExp(/src='([^ ]+)'/i);
		var filter = this.style.filter, src = geturl.exec(filter)[1];
		var ext = src.substring(src.length - 4, src.length), name = src.substring(0, src.length - 9), newSrc = name + ext;
		var dfilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + newSrc + "\', sizingMethod='image')";
		$(this).css({filter:dfilter});

	}
}
if( $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent) )
	$(document).ready(IEroll.init);


// HREF Link
function goTo( url ) {
	location.href = url;
}


/*	Form Highlighting Functions
	--------------------------------------------------------	*/
var liveForm = {
	init : function() {
		var form = $('.form');
		if( form.length <= 0 )
			return false;
		var labels = $(form).find('label');
		var inputs = $(form).find(':input');
		// Hovers
		$(labels).hover( function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); } )
		$(inputs).focus( function(){ $(this).parent().addClass('focus'); } )
		$(inputs).blur( function(){ $(this).parent().removeClass('focus'); } )
	}
}
$(document).ready(liveForm.init);


/* -- Flash Embed -- */
var embed = {
	video : function(type,src,options,target) {
		
		switch( type ) {
			case 'flv' :
			case 'swf' :
				classid = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';
				codebase = 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0';
				pluginspage = 'http://www.macromedia.com/go/getflashplayer';
				apptype = 'application/x-shockwave-flash';
				srcname = 'movie';
				break;
			case 'mov' :
			case 'm4v' :
			case 'mv4' :
				classid = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B';
				codebase = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0';
				pluginspage = 'http://www.apple.com/quicktime/download/';
				apptype = 'application/video-quicktime';
				srcname = 'src';
				break;
			case 'wmv' :
				classid = 'CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6';
				codebase = 'http://activex.microsoft.com/activex/controls/ mplayer/en/nsmp2inf.cab#Version=5,1,52,701';
				pluginspage = 'http://www.microsoft.com/Windows/MediaPlayer/';
				apptype = 'application/x-oleobject';
				srcname = 'FileName';
				break;
		}
		
		// Build Object String
		var objectStr = '<' + 'object classid="' + classid + '" codebase="' + codebase + '" width="' + options.width + '" height="' + options.height + '">' + "\n" + '<' + 'param name="'+ srcname +'" value="' + src + '" />' + "\n";
		for( var key in options ) {
			objectStr += '<' + 'param name="'+ key +'" value="'+ options[key] +'" />' + "\n";
		}
		
		// Build Embed String
		var embedStr = '<' + 'embed src="' + src + '"';
		for( var key in options ) {
			embedStr += ' '+ key + '="' + options[key] + '"';
		}
		embedStr += ' />' + "\n";
		
		objectStr += embedStr + '</' + 'object>' + "\n";
		$(target).html(objectStr);
//		document.write(objectStr);
		
	}
}

/**
 * Parse XML
 */
function xmlToObj(xml,parent_obj) {

	if (parent_obj == null)
	{

		// base object

		var new_obj = {};
		xml = xml.firstChild;

	} else if (xml.nodeName.search(/_array$/) != -1) {

		// array

		var new_obj = parent_obj[xml.nodeName] = [];

	} else if(xml.attributes.length == 0) {

		// node which is really a string attribute

		try {

			parent_obj[xml.nodeName] = xml.firstChild.nodeValue;

		} catch(error) {

			parent_obj[xml.nodeName] = "";

		}

	} else {

		if (parent_obj instanceof Array) {

			//member of an array

			var new_obj = {};
			parent_obj[$(xml).attr('id')] = new_obj;

		} else {

			// new object

			var new_obj = parent_obj[xml.nodeName] = {};

		}				

	}

	// map xml attributes to object properties

	$(xml.attributes).each(function()
	{
		if (this.nodeValue.toLowerCase() == 'true') {

			new_obj[this.nodeName] = true;

		} else if (this.nodeValue.toLowerCase() == 'false') {

			new_obj[this.nodeName] = false;

		} else {

			new_obj[this.nodeName] = parseInt(this.nodeValue);

		}
	});

	if ($(xml).children().length > 0)
	{

		$(xml).children().each(function()
		{
			page_edit.xmlToObj(this, new_obj);

		});

	}

	return new_obj;
}


/**
 * cookies
 *
 * Cookie management in JS.
 */
var cookies = {
	
	set : function( name, value, expires, path, domain, secure )
	{
		var today = new Date();
		today.setTime( today.getTime() );
		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' : '' );

	},
	
	get : function( name )
	{
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 )
			return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 )
			end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	},
	
	remove : function( name, path, domain ) {
		if ( cookies.get( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}

/**
 * slideToggle()
 * 
 * Turns checkboxes into sliding "on/off" switches. Photoshop User theme specific.
 */
jQuery.fn.extend({
	slideToggle : function( options ) {
		return this.each( function(){
			new jQuery.slideToggle( this, options );
		});
	}
});
jQuery.slideToggle  = function( el, options )
{
	var id		= $(el).attr('id');
	var sel		= $(el).attr('checked');
	defaults = {
		start		: 'off'
	}
	options = $.extend(defaults, options);
	
	// Generate toggle image.
	var btn = $('<a></a>').attr('href','#').addClass('btn_toggle').addClass('rt').attr('rel',id).css({backgroundPosition:"0px 0px"});
	$(el).after(btn).css('visibility','hidden').hide();
	
	// Check default.
	if( sel === false ){ turnOff(btn); } else { turnOn(btn); }
	
	// Bind events.
	$(btn).bind( 'click', function( event )
	{
		// Turn On.
		if( $(el).attr('checked') === false ) {
			$(el).attr('checked','checked');
			$(el).change();
			turnOn(this);
		// Turn Off.
		} else {
			$(el).attr('checked','');
			$(el).change();
			turnOff(this);
		}
		return false;
	});
	
	function turnOff( e )
	{
		$(e).stop().animate({backgroundPosition:"(-53px 0px)"}, {duration:150, complete:function(){
			$(this).css({backgroundPosition: "-53px 0px"});
		}});
	}
	
	function turnOn( e )
	{
		$(e).stop().animate({backgroundPosition:"(0px 0px)"}, {duration:150, complete:function(){
			$(this).css({backgroundPosition: "0px 0px"});
		}});
	}
}

jQuery.fn.extend({
	apply: function (){
		var application = arguments[0] || function (){};
		application.apply(this);
		return this;
	}
});
