/*
 * 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: true,
            removable: true,
            collapsible: false,
            editable: true,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual : {
            intro : {
                movable: false,
                removable: false,
                collapsible: false,
                editable: false
            },
			required : {
                movable: true,
                removable: false,
                collapsible: true,
                editable: false
            }
			
        }
		
    },

    init : function () {
        this.attachStylesheet('login/jquery_portal/style/inettuts.js.css');
        this.addWidgetControls();
        this.makeSortable();
    },
    
    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" + ' + ' id="remove">CLOSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('This widget will be removed, ok?')) {
                        //FIND THE ID OF WHAT IS BEING CLOSED
						var parentID = showRef(this);
						
						//MAKE AJAX CALL TO UPDATE DB WITH CHANGE AND REFRESH PAGE
						var params = {};
						var valid = false;

						if(parentID != ''){
							params['ids'] = parentID;
							params['heights'] = 0;
							params['column'] = 0;
							params['active'] = 0;
							valid = true;
						}
						//Call event as POST
						if(valid){
							//UPDATE THE TEMPLATE SETTINGS
							update_template_settings(params, "POST", parentID);
						}		
						
						//HIDE THE MODULE
						$(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: '-38px 0'})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).hide();
							
							var parentID = showRef(this);
							
							
							//MAKE AJAX CALL TO UPDATE DB WITH CHANGE AND REFRESH PAGE
							var params = {};
							var valid = false;
	
							if(parentID != ''){
								params['id'] = parentID;
								params['closed'] = false;
								valid = true;
							}
								
							//Call event as POST
							if(valid){
								//UPDATE WHICH MODULES ARE CLOSED 
								update_closed_modules(params, "POST");
							}		
					
					/*var contentWin = parentID + '_content';
					$(contentWin).css({display:"block",visibility:"visible"});
					if(document.getElementById(contentWin).style.display == 'none' && document.getElementById(contentWin).style.visibility == 'hidden'){
						document.getElementById(contentWin).style.display = 'block';
						document.getElementById(contentWin).style.visibility = 'visible';
					}
					else{
	                    return false;
					}*/
					return false;
			},function () {
                    $(this).css({backgroundPosition: '-52px 0'})
                        .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');
    },
    
    makeSortable : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
                var notSortable = '';
                $(settings.widgetSelector,$(settings.columns)).each(function (i) {
                    if (!iNettuts.getWidgetSettings(this.id).movable) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
				var nStr = (notSortable=='') ? '> li' : '> li:not(' + notSortable + ')' ;
				return $(nStr, settings.columns);
                //return $('> li:not(' + notSortable + ')', settings.columns);
            })();
        
        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mousedown(function (e) {
            $sortableItems.css({width:''});
			//$(this).width('20%');
			$(this).parent().css({
               width: $(this).parent().width() + 'px'
            	//width: '20%'
			});
        }).mouseup(function (e) {
            if(!$(this).parent().hasClass('dragging')) {
                $(this).parent().css({width:''});
            	//$(this).css({width: 'auto'});
				
				var widgetID = $(this).attr("id");
				//var startPos = $(this).offset();

				var xpos = getMousePosition(e);
			
				if(!isNaN(xpos)){
				var currWindowWidth = $(window).width();
				var dropPos = $(this).offset();
				var dropX = dropPos.left;
				colWidthSize = Math.round(currWindowWidth/currNumOfColumns);
				//GET THE COLUMN THAT HAS BEEN CHANGED
				if(xpos < colWidthSize){
					var column = 1;
					resizeCol = '20%';
				}
				else if(xpos > colWidthSize && xpos < (colWidthSize*2)){
					var column = 2;
					resizeCol = '60%';
				}
				else {
					var column = 3;
					resizeCol = '20%';
				}
				
				//LOOP OVER THE COLUMNS AND GET THE NEW HEIGHT VALUES
				var colList = 'weather,calendar,bulletin,press,profile,links,salesbyregion,qtrcommissionpayout,mastersales,topcustomers,enduserpromotions,targetedcustomeraccounts,backorderitems,backordershippable,trendalert';
				myArray = colList.split(",");
				var newHeightList = '';
				var newColList = '';
				
				for(var i=0; i<myArray.length; i++){
					 currPos = $('#' + myArray[i].toUpperCase()).offset();
					 if(currPos != null){					 
						 currCol = currPos.left + 15;//ADD 15 PX TO ENSURE MOVEMENT

						if(column == 1 && currCol < colWidthSize){
							//alert('1module=' + myArray[i] + ',height=' + currPos.top + ',currcol=' + currCol + ',col=' + column + ',id='  + widgetID);
							 newHeightList = addList(newHeightList,currPos.top) ;
							 newColList = addList(newColList,myArray[i]) ;
						  }
						  else if(column == 2 && currCol > colWidthSize && currCol < (colWidthSize*2)){
							 newHeightList = addList(newHeightList,currPos.top) ;
							 newColList = addList(newColList,myArray[i]) ;
						  }
						  else if(column == 3 && currCol > (colWidthSize*2)){
							 newHeightList = addList(newHeightList,currPos.top) ;
							 newColList = addList(newColList,myArray[i]) ;
						  }
					 }
				}

				//MAKE AJAX CALL TO UPDATE DB WITH CHANGE AND REFRESH PAGE
				var params = {};
				var valid = false;
				
				if(widgetID != ''){
					params['ids'] = newColList;
					params['heights'] = newHeightList;
					params['column'] = column;
					params['active'] = 1;
					valid = true;
				}
				
				
				//var stringToSearch = $(this).parent().attr("class");
				var clickTarget = e.target;

				//Call event as POST
				if(newHeightList && clickTarget.toString().indexOf('http:') == -1){
					//alert(newColList + ',' + newHeightList);
					//UPDATE THE ITEM FROM SHOPPING CART					
					update_template_settings(params, "POST", widgetID);
				}					
				}
				else{
					//alert('no');	
				}
				//$(this).css({width: 'auto'});
				width: $(this).parent().width() + 'px';
		} 
			else {
                
				$(settings.columns).sortable('disable');
            }
        });

        $(settings.columns).sortable({
            items: $sortableItems,
            connectWith: $(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 300,
            delay: 100,
            opacity: 0.8,
            containment: 'document',
            start: function (e,ui) {
                $(ui.helper).addClass('dragging');
            },
            stop: function (e,ui) {
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');
			}
        });
    }
  
};

iNettuts.init();

function refresh_page(){
	location.href = 'index.cfm';	
}

function expand_module(id){
	
	var contentWin = id + '_content';
	var arrowHTML = id + '_html';
	
	//MAKE AJAX CALL TO UPDATE DB WITH CHANGE AND REFRESH PAGE
	var params = {};
	var valid = false;

	if(id != ''){
		params['id'] = id;
		params['closed'] = true;
		valid = true;
	}
		
	//Call event as POST
	if(valid){
		//DELETE THE ITEM FROM SHOPPING CART
		update_closed_modules(params, "POST");
	}
	
	$('#'+contentWin).css({display:"block",visibility:"visible"});
	
	if(id=="PROFILE" | id=="LINKS" | id=="BULLETIN"){
		$('#'+arrowHTML).html('<img src="/login/images/open_close.gif" style="margin-left:-5px;"  onclick="javascript: contract_module(' + "'" + id + "'" + ');" onmouseover="this.style.cursor = ' + "'hand'" + ';" />');
	}
	else{
		$('#'+arrowHTML).html('<img src="/login/images/open_close.gif"  onclick="javascript: contract_module(' + "'" + id + "'" + ');" onmouseover="this.style.cursor = ' + "'hand'" + ';" />');
	}
	$('#'+id).css({width:'auto'});
}

function contract_module(id){
	
	var contentWin = id + '_content';
	var arrowHTML = id + '_html';
	
	//MAKE AJAX CALL TO UPDATE DB WITH CHANGE AND REFRESH PAGE
	var params = {};
	var valid = false;

	if(id != ''){
		params['id'] = id;
		params['closed'] = false;
		valid = true;
	}
		
	//Call event as POST
	if(valid){
		//UPDATE WHICH MODULES ARE CLOSED
		update_closed_modules(params, "POST");
	}
	
	$('#'+contentWin).css({display:"none",visibility:"hidden"});
	
	if(id=="PROFILE" | id=="LINKS" | id=="BULLETIN"){
		$('#'+arrowHTML).html('<img src="/login/images/open_close.gif" style="margin-left:-5px;"  onclick="javascript: expand_module(' + "'" + id + "'" + ');" onmouseover="this.style.cursor = ' + "'hand'" + ';" />');
	}
	else{
		$('#'+arrowHTML).html('<img src="/login/images/open_close.gif"  onclick="javascript: expand_module(' + "'" + id + "'" + ');" onmouseover="this.style.cursor = ' + "'hand'" + ';" />');
	}
	$('#'+id).css({width:'auto'});
}
					
function addList(list,value){
	
	var retList = '';
	if(list == '') {
		retList = value;
	}
	else{
		retList = list + ',' + value ;
	}
	return retList;
}


function update_template_settings (params, methodType, wID ) {
	//set event
	var pars = "isAjax=1";
	//Check for Method, else default to GET
	var methodType = (methodType == null) ? "GET" : methodType;
	//parse params
	for(p in params){ 
		pars = pars + "&" + p + "=" + escape(params[p]);
	}
	
	//do Ajax Updater
	$.ajax( {type: methodType, 
		     url:"/login/jquery_portal/update_template_settings.cfm",
		     dataType:"html",
		     data: pars,
		     error: h_callError,
		     complete: h_onComplete,
		     success: function(req){
		     	//IF CHANGE WAS MADE ('DISPLAY|NUMBER OF COLUMNS CURRENTLY AFTER UPDATE' RETURNED) AND THIS IS CALENDAR OR LINKS CHANGE THEN REFRESH BECAUSE JAVASCRIPT BUGS
				//alert(req);
				var retArray = req.split('|');
				if(retArray[0] == 'display' && (wID.toUpperCase() == 'CALENDAR' | wID.toUpperCase() == 'LINKS')){
					refresh_page();
				}
				//IF THE NUMBER OF COLUMNS HAS CHANGED THEN REFRESH WINDOW AUTOMATICALLY
				if(retArray[1] != currNumOfColumns){
					location.href = location.href;
				}
			}
	});
	return false;
}

function update_closed_modules (params, methodType) {
	//set event
	var pars = "isAjax=1";
	//Check for Method, else default to GET
	var methodType = (methodType == null) ? "GET" : methodType;
	//parse params
	for(p in params){ 
		pars = pars + "&" + p + "=" + escape(params[p]);
	}
	
	//do Ajax Updater
	$.ajax( {type: methodType, 
		     url:"/login/jquery_portal/update_closed_settings.cfm",
		     dataType:"html",
		     data: pars,
		     error: h_callError,
		     complete: h_onComplete,
		     success: function(req){
		     	//IF CHANGE WAS MADE ('DISPLAY' RETURNED) AND THIS IS CALENDAR OR LINKS CHANGE THEN REFRESH BECAUSE JAVASCRIPT BUGS
				//alert(params);
			}
	});
	return false;
}

function h_callError(){
	return false;
}

function h_onComplete(){
	return false;
}

function showRef(formElement){
	var parentDiv = findParentDiv(formElement);
	if(parentDiv){
		//alert("found: " + parentDiv.id);
		return(parentDiv.id);
	}
	//else{
		//alert("unable to locate parent div");
	//}
}

function findParentDiv(elem){
	var parent = elem.parentNode;
	if(parent && parent.tagName.toUpperCase()!="DIV"){
		parent = findParentDiv(parent);
	}
	return parent;
}

function getMousePosition(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return posx;
	
}
