// guistuff.js

function Dialog(dialogId){
	this.id					= dialogId;
	this.height			= 150;
	this.width 			= 200;
	this.url				= false;
	this.title			= '';
	this.imageId		= false;
	this.onclose		= function(){};
	this.closeImg 	= 'close-small.gif';
	this.showTitle	= true;
	this.contentDiv	= false;
	this.modal 			= true;
	this.shadow			= false;
	this.backColor		= '#fff';
}

Dialog.prototype.show = function(imageId) {
	// only proceed if we haven't before
	if(document.getElementById(this.id) != null) return false;
	
	// imageId is an optional parameter
	this.imageId = (typeof imageId == 'undefined'?false:imageId);

	var bodyEl = document.getElementsByTagName("body")[0];
	var divEl = document.createElement("div");
	
	divEl.id = this.id;
	divEl.className = 'guiDialog';
	divEl.style.visibility = 'hidden';
	divEl.style.backgroundColor = this.backColor;
	
	var scrollPos = gs_getScrollingPosition();
	var viewSize = gs_getViewportSize();
	var pageDim = gs_getPageDimensions();
	
	if(viewSize[1] > pageDim[1]) pageDim[1] = viewSize[1];
	
	// create the overlay
	if(this.modal){
		var overlayEl = document.createElement("div");
		overlayEl.id = 'overlay';
		//overlayEl.style.height = ((viewSize[1] > bodyEl.offsetHeight)?viewSize[1]:bodyEl.offsetHeight + 30) + 'px';
		//overlayEl.style.width = ((viewSize[0] > bodyEl.offsetWidth)?viewSize[0]:bodyEl.offsetWidth + 30) + 'px';
		overlayEl.style.height = pageDim[1] + 'px';
		overlayEl.style.width = pageDim[0] + 'px';
	}

	// create the titlebar
	var titleBarEl = document.createElement("div");
	titleBarEl.id = this.id + '_titleBar';
	titleBarEl.className = 'guiTitlebar';
	
	// create the close button
	var closeEl = document.createElement('a');
	var closeImgEl = document.createElement('img');
	closeImgEl.src = this.closeImg;
	closeEl.style.border = 'none';
	closeEl.style.cssFloat = 'right';
	closeEl.style.styleFloat = 'right';
	closeEl.appendChild(closeImgEl);
	closeEl.href='javascript:Dialog_Dispose(\'' + this.id + '\');';
	closeEl.onclick = this.onclose;
	
	// add the titlebar text
	titleBarEl.appendChild(closeEl);
	titleBarEl.appendChild(document.createTextNode(this.title));
	
	//add the title bar
	if(this.showTitle)
		divEl.appendChild(titleBarEl);
	
	// add the dialog box to the document
	bodyEl.appendChild(divEl);
	
	//add iframe if url specified
	if(this.url != false){
		var iframe = document.createElement('iframe');
		iframe.src = this.url
		iframe.frameBorder = '0';
		iframe.scrolling = 'no';
		iframe.style.border = 'none';
		iframe.style.width = this.width + 'px';
		iframe.style.height = this.height - (this.showTitle?titleBarEl.offsetHeight:0) + 'px';
		divEl.appendChild(iframe);
	}
	
	// add image if image specified
	if(this.imageId != false){
		var imageViewEl = new Image();
		var pageImageEl = document.getElementById(this.imageId);
		imageViewEl.src = pageImageEl.src;
		imageViewEl.style.margin = '10px 10px';
		// set window size to image size
		this.height = imageViewEl.height + (this.showTitle?titleBarEl.offsetHeight:0) + 20;
		this.width = imageViewEl.width + 20;
		divEl.appendChild(imageViewEl);
	}
	
	if(this.contentDiv != false){
		var content = document.getElementById(this.contentDiv);
		if(typeof content != 'undefined'){
			var contentDiv = document.createElement('div');
			contentDiv.style.overflow = 'hidden';
			contentDiv.style.width = this.width + 'px';
			contentDiv.style.height = this.height - (this.showTitle?titleBarEl.offsetHeight:0) + 'px';
			contentDiv.innerHTML = content.innerHTML;
			divEl.appendChild(contentDiv);
		}
	}

	var top = scrollPos[1] + (viewSize[1] - this.height)/2;
	var left = scrollPos[0] + (viewSize[0] - this.width)/2;
	
	// set the size and position
	divEl.style.height = this.height + 'px';
	divEl.style.width = this.width + 'px';
	divEl.style.left = left + 'px';
	divEl.style.top = top + 'px';
	
	// drop shadow
	if(this.shadow){
		var shadowEl = document.createElement("div");
		shadowEl.className = 'guiShadow';
		shadowEl.id = 'guiShadow';
		shadowEl.style.height = this.height + 'px';
		shadowEl.style.width = this.width + 'px';
		shadowEl.style.left = left + 6 + 'px';
		shadowEl.style.top = top + 6 + 'px';
		bodyEl.appendChild(shadowEl);
	}
	
	// hide all the select elements
	gs_toggleSelects('hidden');
	
	// add the overlay to the document
	if(this.modal) 
		bodyEl.appendChild(overlayEl);
	
	// show the div element
	divEl.style.visibility = 'visible';

	// attach drag events
	titleBarEl.onmousedown = function(event){
		var event = (typeof event == 'undefined')?window.event:event;
		if((typeof this.id != 'undefined') && (gs_getEventTarget(event).id.indexOf('_titleBar') > 0)){
			document.dragObject = gs_getEventTarget(event).parentNode;
			document.dragObjectShadow = document.getElementById('guiShadow');
			if(document.dragObjectShadow == null)
				document.dragObjectShadow = {style:{left:'',top:''}};
			document.offsetX = (event.clientX + scrollPos[0]) - document.dragObject.offsetLeft;
			document.offsetY = (event.clientY + scrollPos[1]) - document.dragObject.offsetTop;
			// cancel out any text selections 
			document.body.focus();
			document.onselectstart = function(){return false;};
			// if we're dealing with an iframe it needs to be hidden
			var iframes = document.dragObject.getElementsByTagName('iframe');
			if(iframes[0] != null)iframes[0].style.display = 'none';
			document.onmousemove = function(event){
				if(document.dragObject == null){
					document.onmousemove = null;
					document.onmouseup = null;
					document.onselectstart = null;
				}else{
					var event = (typeof event == 'undefined')?window.event:event;
					document.onmouseup = function(event){
						// restore any hidden iframes
						var iframes = document.dragObject.getElementsByTagName('iframe');
						if(iframes[0] != null)iframes[0].style.display = '';
						document.dragObject = null;
					};
					document.dragObject.style.top = event.clientY + scrollPos[1] - document.offsetY + 'px';
					document.dragObject.style.left = event.clientX + scrollPos[0] - document.offsetX + 'px';
					document.dragObjectShadow.style.top = event.clientY + scrollPos[1] - document.offsetY + 6 + 'px';
					document.dragObjectShadow.style.left = event.clientX + scrollPos[0] - document.offsetX + 6 + 'px';
				}
			};
			return false;
		}
	};
	return false;
};

Dialog.prototype.dispose = function(){
	if(document.getElementById(this.id) != null)
		this.onclose();
	Dialog_Dispose(this.id);
	return false;	
};

Dialog.prototype.close = function(){
	if(document.getElementById(this.id) != null)
		this.onclose();
	Dialog_Dispose(this.id);
	return false;
};

function Dialog_Dispose(dialogId) {
	var divEl = document.getElementById(dialogId);

	if(typeof divEl != 'undefined'){
		divEl.parentNode.removeChild(divEl);
		
		var mask = document.getElementById(divEl.id + '_mask');
		if(typeof mask != 'undefined' && mask != null) mask.parentNode.removeChild(mask);
		
		// remove the overlay
		var overlayEl = document.getElementById('overlay');
		if(typeof overlayEl != 'undefined' && overlayEl != null)
			overlayEl.parentNode.removeChild(overlayEl);
			
		// remove the shadow
		var shadowEl = document.getElementById('guiShadow');
		if(typeof shadowEl != 'undefined' && shadowEl != null)
			shadowEl.parentNode.removeChild(shadowEl);
		
		// show all the select elements
		gs_toggleSelects('visible');
	}
}


function ToolTips(){
	this.bgcolor = '#fff';
	this.color = '#000';
	this.data = false;
	this.cssClass = 'tooltip';
	this.delay = 500;
}

ToolTips.prototype.init = function(){
	var labels = document.getElementsByTagName('label');
	for(var i=0; i < labels.length; i++){
		var label = labels[i];
		if(label.title != ''){
			var forEl = document.getElementById(label.htmlFor);
			forEl.toolTip = new ToolTip(label.firstChild.nodeValue, label.title, forEl);
			gs_attachEventListener(forEl, 'mouseover', showToolTip, false);
			gs_attachEventListener(forEl, 'mouseout', hideToolTip, false);
			//attachEventListener(forEl, 'click', hideToolTip, false);
		}
	}
}

function ToolTip(title, content, owner){
	this.content = content;
	this.title = title;
	this.owner = owner;
	this.div = null;
}

ToolTip.prototype.show = function(){
	var tip = document.createElement('div');
	this.div = tip;

	var titleTag = document.createElement('h1');
	titleTag.appendChild(document.createTextNode(this.title));
	tip.appendChild(titleTag);
	tip.appendChild(document.createTextNode(this.content));

	var ownerPos = findPos(this.owner);
	
	tip.className = document.toolTips.cssClass;
	tip.style.backgroundColor = document.toolTips.bgcolor;
	tip.style.position = 'absolute';

	tip.style.left = ownerPos[0] + this.owner.offsetWidth + 10 + 'px';
	tip.style.top = ownerPos[1] + 'px';

	document.getElementsByTagName('body')[0].appendChild(tip);
}

ToolTip.prototype.showDelay = function(){
	var self = this;
	this.timer = setTimeout(function(){self.show()}, document.toolTips.delay);
}

ToolTip.prototype.hide = function(){
	if(typeof this.timer != 'undefined'){
		clearTimeout(this.timer);
	}
	if(this.div != null){
		this.div.parentNode.removeChild(this.div);
		this.div = null;
	}
}

function showToolTip(){
	this.toolTip.showDelay();
}

function hideToolTip(event){
	this.toolTip.hide(event);
}

function showToolTip_old(event){
	event = (event == 'undefined')?window.event:event;
	if(document.toolTips == 'undefined') return;
	
	var tip = document.createElement('div');
	var content = document.toolTips.data[this.id];
	
	this.toolTip = tip;
	tip.id = this.id + '_tooltip';
	
	tip.appendChild(document.createTextNode(content));
	
	var scrollPos = getScrollingPosition();
	var cursorPos = [0,0];
	
	if(typeof event.pageX != 'undefined' && typeof event.x != 'undefined'){
		cursorPos[0] = event.pageX;
		cursorPos[1] = event.pageY;
	}else{
		cursorPos[0] = event.clientX + scrollPos[0];
		cursorPos[1] = event.clientY + scrollPos[1];
	}
	
	tip.style.backgroundColor = document.toolTips.bgcolor;
	tip.style.color = document.toolTips.color;
	tip.style.border = '1px solid silver';
	tip.style.padding = '5px';
	tip.style.position = 'absolute';
	tip.style.left = cursorPos[0] + 10 + 'px';
	tip.style.top = cursorPos[1] + 10 + 'px';
	document.getElementsByTagName('body')[0].appendChild(tip);
}

function hideToolTip_old(event){
	event = (event == 'undefined')?window.event:event;
	
	if(this.toolTip == null) return;
	
	this.toolTip.parentNode.removeChild(this.toolTip);
	this.toolTip = null;
}


function gs_createMask(obj){
	var iframe = document.createElement('iframe');

	iframe.src = 'javascript:false;';
	iframe.tabIndex = '-1';
	iframe.style.border = 'none';
	iframe.style.position = 'absolute';
	iframe.style.zIndex = '9998';
	iframe.id = obj.id + '_mask';
	iframe.style.top = obj.offsetTop + 'px';
	iframe.style.left = obj.offsetLeft + 'px';
	iframe.style.width = obj.offsetWidth + 'px';
	iframe.style.height = obj.offsetHeight + 'px';
	obj.parentNode.appendChild(iframe);
}

function gs_getEventTarget(event){
	if(typeof event.target == 'undefined'){
		return event.srcElement;
	}else{
		return event.target;
	}
}

function gs_getScrollingPosition(){
 var position = [0, 0];

 if (typeof window.pageYOffset != 'undefined')
 {
   position = [
       window.pageXOffset,
       window.pageYOffset
   ];
 }

 else if (typeof document.documentElement.scrollTop
     != 'undefined' && document.documentElement.scrollTop > 0)
 {
   position = [
       document.documentElement.scrollLeft,
       document.documentElement.scrollTop
   ];
 }

 else if (typeof document.body.scrollTop != 'undefined')
 {
   position = [
       document.body.scrollLeft,
       document.body.scrollTop
   ];
 }

 return position;
}

function gs_getViewportSize(){
 var size = [0, 0];

 if (typeof window.innerWidth != 'undefined')
 {
   size = [
       window.innerWidth,
       window.innerHeight
   ];
 }
 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
   size = [
       document.documentElement.clientWidth,
       document.documentElement.clientHeight
   ];
 }
 else
 {
   size = [
       document.getElementsByTagName('body')[0].clientWidth,
       document.getElementsByTagName('body')[0].clientHeight
   ];
 }

 return size;
}

function gs_getPageDimensions() {
	var body = document.getElementsByTagName('body')[0];
	var bodyOffsetWidth = 0;
	var bodyOffsetHeight = 0;
	var bodyScrollWidth = 0;
	var bodyScrollHeight = 0;
	var pageDimensions = [0,0];
	
	if (typeof document.documentElement != 'undefined' && typeof document.documentElement.scrollWidth != 'undefined'){
			pageDimensions[0] = document.documentElement.scrollWidth;
			pageDimensions[1] = document.documentElement.scrollHeight;
	}
	
	bodyOffsetWidth = body.offsetWidth;
	bodyOffsetHeight = body.offsetHeight;
	bodyScrollWidth = body.scrollWidth;
	bodyScrollHeight = body.scrollHeight;
	
	if (bodyOffsetWidth > pageDimensions[0]) pageDimensions[0] = bodyOffsetWidth;
	
	if (bodyOffsetHeight > pageDimensions[1]) pageDimensions[1] = bodyOffsetHeight;
	
	if (bodyScrollWidth > pageDimensions[0]) pageDimensions[0] = bodyScrollWidth;
	
	if (bodyScrollHeight > pageDimensions[1]) pageDimensions[1] = bodyScrollHeight;
	
	return pageDimensions;
}

function gs_findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		// this loop will continue until offsetParent doesn't exist and obj evals to null
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function gs_attachEventListener(target, eventType, functionRef, capture){
	if(typeof target.addEventListener != 'undefined'){
		target.addEventListener(eventType, functionRef, capture);
	}else if(typeof target.attachEvent != 'undefined'){
		var functionString = eventType + functionRef;
		target['e' + functionString] = functionRef;
		
		target[functionString] = function(event){
			if(typeof event == 'undefined'){
				event = window.event;
			}
			target['e' + functionString](event);
		};
		target.attachEvent('on' + eventType, target[functionString]);
	}else{
		eventType = 'on' + eventType;
		
		if(typeof target[eventType] == 'function'){
			var oldListener = target[eventType];
			target[eventType] = function(){
				oldListener();
				return functionRef();
			};
		}else{
			target[eventType] = functionRef;
		}
	}
}

function gs_detachEventListener(target, eventType, functionRef, capture){
	if(typeof target.removeEventListener != 'undefined'){
		target.removeEventListener(eventType, functionRef, capture);
	}else if(typeof target.detachEvent != 'undefined'){
		var functionString = eventType + functionRef;
		target.detachEvent('on' + eventType, target[functionString]);
		target['e' + functionString] = null;
		target[functionString] = null;
	}else{
		target['on' + eventType] = null;
	}
}

function gs_toggleSelects(visibility){
	if(!document.all) return false;
    selects = document.getElementsByTagName('select');
    for(i = 0; i < selects.length; i++) {
        selects[i].style.visibility = visibility;
    }
}




//Brand URLS

var url = document.location.href;
var data;
var numImages;

//Images to Display based on Location

if (url.indexOf("/auto/") > -1 || url.indexOf("_auto") > -1){
	    
	data = "/root/binary/johnson/images/brandBar/auto/";
	numImages = 2;
	    
}else if (url.indexOf("/home/") > -1 || url.indexOf("_home") > -1){

	data = "/root/binary/johnson/images/brandBar/home/";
	numImages = 2;
	
}else if (url.indexOf("planbenefit") > -1){

	data = "/root/binary/johnson/images/brandBar/planbenefit/";
	numImages = 1;
	
}else if (url.indexOf("about_careers.jspx") > -1){

	data = "/root/binary/johnson/images/brandBar/career/";
	numImages = 1;
	
}else if (url.indexOf("about_contact") > -1){
	
	data = "/root/binary/johnson/images/brandBar/contact/";
	numImages = 1;

}else if (url.indexOf("about") > -1){
	
	data = "/root/binary/johnson/images/brandBar/about/";
	numImages = 1;
	
}else if (url.indexOf("learn") > -1){

	data = "/root/binary/johnson/images/brandBar/learn/";
	numImages = 1;

}else if (url.indexOf("claims") > -1){

	data = "/root/binary/johnson/images/brandBar/claims/";
	numImages = 1;

}else{

	data = "/root/binary/johnson/images/brandBar/";
	numImages = 1;
}


// Change Font Size 

	var sizeCount = 0;
	var sizePref = 0;
	var textSize= new Array(1, 1.2, 1.3, 1.4)

	function decreaseFontSize()
	{
		if(sizeCount != 0)
		{
			sizeCount = parseInt(sizeCount);
		}
		sizeCount = sizeCount-1;
		if(sizeCount <= 0)
		{
			sizeCount = 0;
		}
		document.getElementById("contentArea").style.fontSize = textSize[sizeCount]+"em";
		

		createCookie('textSize_pref', sizeCount, 365);
		
	}
	
	function increaseFontSize(tSize)
	{
		if(sizeCount != 0)
		{
			sizeCount = parseInt(sizeCount);
		}
		
		var textOptLength = textSize.length-1;
		
		if(tSize != null) {
			sizeCount = tSize;
		} else {
			sizeCount = sizeCount+1;
		}
		if(sizeCount >= textOptLength)
		{
			sizeCount = textOptLength;
		}	
		document.getElementById("contentArea").style.fontSize = textSize[sizeCount]+"em";
		
		createCookie('textSize_pref', sizeCount, 365);                                          
	} 
	
/* Cookie Set Up*/

	function createCookie(name,value,days) {
	  if (days) {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
	  }
	  else var expires = "";
	  document.cookie = name+"="+value+expires+"; path=/";
	}
	 
	function readCookie(name) {
	  var nameEQ = name + "=";
	  var ca = document.cookie.split(';');
	  for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	  }
	  return null;
	}

/* Read Cookie */

	function textSizePref()
		{
			var cookie = readCookie("textSize_pref");
			if(cookie > 0)
			{
				increaseFontSize(cookie)
			}
		}

//Dialog Control


function submitMyResume(jobId)
{
   var submitResume = new Dialog("submitResume");
   submitResume.width = 440;
   submitResume.height = 375;
   submitResume.title = "Submit Resume";
   submitResume.url = "/PWS_Site/english_content/Submit_Resume.jsp?jobno=" + jobId;
   submitResume.closeImg = "/root/binary/johnson/images/close-small.jpg";
   submitResume.showTitle = true;
   submitResume.show();
}

function viewJob(jobId)
{
   var jobDialog = new Dialog("jobDialog");
   jobDialog.width = 545;
   jobDialog.height = 570;
   jobDialog.title = "View Job";
   jobDialog.url = "/english/ViewJob?id=" + jobId;
   jobDialog.closeImg = "/root/binary/johnson/images/close-small.jpg";
   jobDialog.showTitle = true;
   jobDialog.show();
}

//Address Utils

// redirect to proper content page based on submitted postal code
// requires service variable
function contactUs(frm, postalCode, errorMsg){
	var prov = frm.elements['prov'];
	var srv = frm.elements['service'];
	srv.value = service;
        if (postalCode.match(/[A]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_nl.jspx?prov=NL&pc='+postalCode+'&svc='+service;
  	  prov.value='NL';
	} else if (postalCode.match(/[B]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_ns.jspx?prov=NS&pc='+postalCode+'&svc='+service
  	  prov.value='NS';

	} else if (postalCode.match(/[C]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_pe.jspx?prov=PE&'+postalCode+'&svc='+service
  	  prov.value='PE';

	} else if (postalCode.match(/[E]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_nb.jspx?prov=NB&pc='+postalCode+'&svc='+service
  	  prov.value='NB';

	} else if (postalCode.match(/[GHJ]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_on.jspx?prov=QU&pc='+postalCode+'&svc='+service
  	  prov.value='QU';

	} else if (postalCode.match(/[KLMNP]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_on.jspx?prov=ON&pc='+postalCode+'&svc='+service
  	  prov.value='ON';

	} else if (postalCode.match(/[R]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_ab.jspx?prov=MB&pc='+postalCode+'&svc='+service
  	  prov.value='MB';

	} else if (postalCode.match(/[S]\d[A-Z]\s?\d[A-Z]\d/i)){
  	  url = '/root/about/about_contact_ab.jspx?prov=SK&pc='+postalCode+'&svc='+service
  	  prov.value='SK';

	} else if (postalCode.match(/[T]\d[A-Z]\s?\d[A-Z]\d/i)){
	  url = '/root/about/about_contact_ab.jspx?prov=AB&pc='+postalCode+'&svc='+service
  	  prov.value='AB';

	} else if (postalCode.match(/[V]\d[A-Z]\s?\d[A-Z]\d/i)){
	  url = '/root/about/about_contact_bc.jspx?prov=BC&pc='+postalCode+'&svc='+service
  	  prov.value='BC';

	} else if (postalCode.match(/[X]\d[A-Z]\s?\d[A-Z]\d/i)){
	  url = '/root/about/about_contact_ab.jspx?prov=NU&pc='+postalCode+'&svc='+service
  	  prov.value='NU';

	} else if (postalCode.match(/[Y]\d[A-Z]\s?\d[A-Z]\d/i)){
	  url = '/root/about/about_contact_ab.jspx?prov=YT&pc='+postalCode+'&svc='+service
  	  prov.value='YT';

    } else {	
	  alert(errorMsg);
   	  prov.value='UK';
	  return false;
	}

	var location = window.location.protocol + '//' + window.location.host ;
	var newlocation = location +''+ url ;
	frm.action=newlocation;

	
	return true;
}


//Careers Interface

/*
 * Script from NETTUTS.com [by James Padolsey]
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules
 */

var iNettuts = {
    
    jQuery : $,
    
    settings : {
        columns : '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        widgetDefault : {
            movable: false,
            removable: false,
            collapsible: true,
            editable: false,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual : {
            intro : {
                movable: false,
                removable: false,
                collapsible: false,
                editable: false
            }
        }
    },

    init : function () {
        this.attachStylesheet('/root/binary/johnson/css/widget.css');
        this.addWidgetControls();
    },
    
    getWidgetSettings : function (id) {
        var $ = this.jQuery,
            settings = this.settings;
        return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
    },
    
    addWidgetControls : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
            
        $(settings.widgetSelector, $(settings.columns)).each(function () {
            var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
            if (thisWidgetSettings.removable) {
                $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('This widget will be removed, ok?')) {
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            $(this).wrap('<div/>').parent().slideUp(function () {
                                $(this).remove();
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
            
            if (thisWidgetSettings.editable) {
                $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).css({backgroundPosition: '-66px 0', width: '55px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input').focus();
                    return false;
                },function () {
                    $(this).css({backgroundPosition: '', width: ''})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
                    return false;
                }).appendTo($(settings.handleSelector,this));
                $('<div class="edit-box" style="display:none;"/>')
                    .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
                    .append((function(){
                        var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
                        $(thisWidgetSettings.colorClasses).each(function () {
                            colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
            }
            
            if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).css({backgroundPosition: '-14px 0'})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).hide();
                    return false;
                },function () {
                    $(this).css({backgroundPosition: ''})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).show();
                    return false;
                }).prependTo($(settings.handleSelector,this));
            }
        });
        
        $('.edit-box').each(function () {
            $('input',this).keyup(function () {
                $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
            });
            $('ul.colors li',this).click(function () {
                
                var colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
                if (thisWidgetColorClass) {
                    $(this).parents(settings.widgetSelector)
                        .removeClass(thisWidgetColorClass[0])
                        .addClass($(this).attr('class').match(colorStylePattern)[0]);
                }
                return false;
                
            });
        });
        
    },
    
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    }
  
};

iNettuts.init();