/* 
	File name: tracking-grid.cache.js
	Description: This is used on tracking home page and tracking input page, helps in managing history grid
	Revision	: $Revision: $
	Created by: Nagesh Arra
	Modified by	: $Author: xhc6qdb $ $Date: 2009/03/13 20:20:06 $
	Checkout Tag	: $Name:  $
	
	Copyright 2009 United Parcel Service of America, Inc. All Rights Reserved.
*/

(function() {
    var gridTop;
    var gridLeft;
    var minColumnWidth = 30;
    var isMouseDownOnGrid = false;
    var gridResizeSourceId;
    var initDone = false;
    var diff;
    var vResizerPos;

	/**
	 * returns mouse co-ordinates using event
	 */		
    function mouseCoords(event){
        if(event.pageX || event.pageY){
             return {x:event.pageX, y:event.pageY};
         }
         return {
             x:event.clientX + document.body.scrollLeft - document.body.clientLeft,
             y:event.clientY + document.body.scrollTop  - document.body.clientTop
         };
    }

	/**
	 * handling mouse move on grid
	 */		
    function mouseMove(event) {
        var ev = event || window.event;
        //alert(ev);
        var point = mouseCoords(ev);
        if(isMouseDownOnGrid) {
            //alert("mouse drag ");
            //alert(isMouseDownOnGrid);

            //Identifying which column resize is clicked
            var $resizer = $("[@id="+gridResizeSourceId+"]");
            if($resizer.attr("class")=="trk-grid-hResizer"){
                //alert("column resize");
                document.body.style.cursor = 'e-resize';
                handleColumnResize($resizer, point);
            }else if($resizer.attr("class")=="trk-grid-vResizer") {
                //alert("grid resize");
                document.body.style.cursor = 'n-resize';
                handleGridResize($resizer, point);
            }
            //alert("resize done");
        } else {
            //alert("mouse moved");

            //Setting default cursor back
            document.body.style.cursor = 'default';
        }
    }

	/**
	 * handling grid height resize (vertical)
	 */		
    function handleGridResize($resizer, point) {
        var gridId = "trk-grid-0";
        var bodyId = "trk-grid-body-0";
        var headerId = "trk-grid-col-hdr-0";
        var $gridRoot = $("[@id="+gridId+"]");
        var $gridBody = $("[@id="+bodyId+"]");
        var $gridHeader = $("[@id="+headerId+"]");
        //alert("header height str"+$gridHeader.css("height"));
        var headerHeight = parseInt($gridHeader.css("height"));
        //alert("header height"+headerHeight);
        var newHeight = point.y-gridTop;
        //alert("body id="+$gridRoot.attr("id"));
        //alert(point.y+" "+newHeight+" "+gridTop+" "+gridId+" "+gridResizeSourceId);
        //restrict minimum height to 3 rows (125px) and maximum height to 75 rows (1875)
        if (newHeight-headerHeight>75 && newHeight-headerHeight<1875) {
            $gridRoot.css("height", newHeight-diff);
            $resizer.css("top",newHeight-diff);
            $gridBody.css("height", newHeight-headerHeight-diff);
        }
    }

	/**
	 * handling grid column resize (horizontal) 
	 */		
    function handleColumnResize($resizer, point) {

        //Identifying the columns and headers to be resized
        var col = $resizer.attr("col");
        var lHId = "trk-grid-col-hdr-"+col;
        var rHId = "trk-grid-col-hdr-"+(parseInt(col)+1);
        var lCId = "trk-grid-col-"+col;
        var rCId = "trk-grid-col-"+(parseInt(col)+1);
        
        //switch columns for he_IL
        if(Tracking.getLocaleString()=='he_IL') {
        	var temp = lHId;
        	lHId = rHId;
        	rHId = temp;
        	
        	temp = lCId;
        	lCId = rCId;
        	rCId = temp;  
        }
        
        var gridId = "trk-grid-0";
        //alert(gridId);
        var gridQuery = "div.trk-grid[@id="+gridId+"]";
        var $gridRoot = $(gridQuery);

        //alert($gridRoot.attr("id")+","+lHId+","+rHId+","+lCId+","+rCId);
        var $leftHeader = $gridRoot.find("div[id="+lHId+"]");
        var $rightHeader = $gridRoot.find("div[id="+rHId+"]");
        var $leftColumn = $gridRoot.find("div[id="+lCId+"]");
        var $rightColumn = $gridRoot.find("div[id="+rCId+"]");

        //Original left and width properties of headers
        var l1 = parseInt($leftHeader.css("left"));
        var l2 = parseInt($rightHeader.css("left"));
        var w2 = parseInt($rightHeader.css("width"));

        //Mouse pointer position
        var cX = point.x;

        //Restricting resize
        if(cX<gridLeft+l1)	{ cX = gridLeft+l1;		}
        if(cX>gridLeft+l2+w2){ cX = gridLeft+l2+w2;	}

        //alert($leftHeader.attr("id")+", "+$rightHeader.attr("id")+", "+$leftColumn.attr("id")+", "+$rightColumn.attr("id"));
        //Resizing
        var leftWidth = cX-l1-gridLeft;
        var rightWidth = l2+gridLeft-cX+w2;
        if(leftWidth>=minColumnWidth && rightWidth>=minColumnWidth) {
            $leftHeader.css("width", leftWidth);
            $rightHeader.css("width", rightWidth);
            $rightHeader.css("left", cX-gridLeft);
            $resizer.css("left",cX-gridLeft);

            //alert("header resize done");
            //Resize column data
            $leftColumn.css("width", leftWidth);
            $rightColumn.css("width", rightWidth);
            $rightColumn.css("left", cX-gridLeft);
        }

    	//alert("Column Resize ends");
        //statusDiv.innerHTML = "leftCol width:"+(cX-l1-gridLeft)+" lcW:"+$leftColumn.css("width");
    }
    
    /**
     * Mouse down handled here, resize starts with this call
     */
    function mouseDown(resizerId, event) {
        //alert("down " + resizerId);
        
        document.body.focus();
        if(event.preventDefault) {  event.preventDefault(); }
        
        gridResizeSourceId=resizerId;
        isMouseDownOnGrid = true;
        disableGridSelection("trk-grid-0");
        initGrid();
        if(resizerId=="trk-grid-0_resizerBottom") {
	        var ev = event || window.event;
	        var point = mouseCoords(ev);
	        if(diff==undefined) {
	            diff = point.y-vResizerPos.y;
	            //alert(diff);
	        }
	    }
    }

    /**
     * Mouse up handled here, resize ends with this call
     * @ depricated
     */
    function mouseUp(resizerId) {
        //alert("up " + resizerId);
        alert("this method is depricated and should not be called");
        isMouseDownOnGrid = false;
        gridResizeSourceId = null;
        enableGridSelection("trk-grid-0");
        //alert("Mouse up on: " + event.srcElement.id);
    }

	/**
	 * Grid initialization with its x and y locations (left and top)
	 */		
    function initGrid() {
        //alert("init Grid");
        if(initDone) { return;}
        initDone = true;
        var gridPos = findPos(document.getElementById("trk-grid-0"));
        gridLeft = gridPos.x;
        gridTop = gridPos.y;
        if(document.getElementById("trk-grid-0_resizerBottom")) {
        	vResizerPos = findPos(document.getElementById("trk-grid-0_resizerBottom"));
        }
        //alert("x:"+gridLeft+" y:"+gridTop);
    }

	/**
	 * find absolute position of an element (left and top), returns point(x,y)
	 */		
    function findPos(obj) {
        var curLeft = 0;
        var curTop = 0;
        if (obj.offsetParent) {
            while (1) {
                curLeft += obj.offsetLeft;
                curTop += obj.offsetTop;
                if (!obj.offsetParent) {
                    break;
                }
                obj=obj.offsetParent;
            }
        } else if (obj.x && obj.y) {
            curLeft += obj.x;
            curTop += obj.y;
        }
        return new Point(curLeft, curTop);
    }


	/**
	 * wrapper for point (x,y)
	 */		
    function Point(x, y)    {
        this.x = x;
        this.y = y;
        return this;
    }

	/**
	 * wrapper for disableSel, only for convenience of commenting this logic if needed
	 */		
    function disableGridSelection(targetId){ 
        disableSel(targetId);
    }

	/**
	 * Disable selection of grid as it conflicts with dragging
	 */		
    function disableSel(targetId) {
        var target = document.getElementById(targetId);
        //var target = document;
        if (typeof target.onselectstart!="undefined") { //IE route
            //alert("disable for IE");
            target = document;
            target.onselectstart=function(){return false}
        }
        else if (typeof target.style.MozUserSelect!="undefined") { //Firefox route
            //alert("disabled for FF "+target.style.MozUserSelect);
            target.style.MozUserSelect="none"
        }
        else {//All other route (ie: Opera)
            target.onmousedown=function(){return false}
        }
        //alert("disable end");
    }

	/**
	 * wrapper for enableSel, only for convenience of commenting this logic if needed
	 */		
    function enableGridSelection(targetId){
        //alert("enable");
        enableSel(targetId);
    }

	/**
	 * Enable selection of grid after dragging action is done
	 */		
    function enableSel(targetId) {
        var target = document.getElementById(targetId);
        //var target = document;
        if (typeof target.onselectstart!="undefined") { //IE route
            //alert("enabled for IE ");
            target = document;
            target.onselectstart=null;
        }
        else if (typeof target.style.MozUserSelect!="undefined") { //Firefox route
            //alert("enabled for FF ");
            target.style.MozUserSelect="";
        }else { //All other route (ie: Opera)
            target.onmousedown=null;
        }
    }

	/**
	 * Set absolute width from percentage width, after the page load.
	 * This helps load the grid for different homepage layouts (narrow, medium and wide)
	 */	
    function setAbsoluteWidth() {
    	 //alert("home page tracking app -- set absolute width -- start");  
        var ContainerWidth = $("#Tracking").parent().width();
        //alert(ContainerWidth);
        $("div.trk-grid-col-hdr").each( function(i,obj){
            percentageWidth = parseFloat(obj.style.width);
            percentageLeft = parseFloat(obj.style.left);
            //alert(obj.style.left+" = "+percentageLeft);
            absoluteWidth = (percentageWidth*ContainerWidth)/100;
            absoluteLeft = (percentageLeft*ContainerWidth)/100;
            //alert(absoluteWidth);
            obj.style.width = absoluteWidth+"px";
            obj.style.left = absoluteLeft+"px";
        });

        $("div.trk-grid-col").each( function(i,obj){
            percentageWidth = parseFloat(obj.style.width);
            percentageLeft = parseFloat(obj.style.left);
            //alert(percentageWidth);
            absoluteWidth = (percentageWidth*ContainerWidth)/100;
            absoluteLeft = (percentageLeft*ContainerWidth)/100;
            //alert(absoluteWidth);
            obj.style.width = absoluteWidth+"px";
            obj.style.left = absoluteLeft+"px";
        });
    }

	/**
	 * Adjust the resizer to match absolute width after adjusting % width to pixel width
	 */		
    function adjustResizer() {
        var ContainerWidth = $("#trk-grid-0").parent().width();
        
        if(Tracking.getLocaleString()=='he_IL') {
        	//36.36 is the width of status column as status will be first for this locale
        	$("[id=trk-grid-0_resizer-1]").css("left",(36.36*ContainerWidth)/100);
        }else {
        	//63.64 is the sum of widths of check box column and recent tracks column
	        $("[id=trk-grid-0_resizer-1]").css("left",(63.64*ContainerWidth)/100);
        }
    }


	/**
	 * Handling mouse up on document (outside grid), this helps in stopping dragging even if the 
	 * user drag away from the grid area
	 */		
    function mouseUpOnDocument() {
        //alert("my mouse up");
        if(isMouseDownOnGrid) {
        	document.getElementById("trk-grid-0").focus();
        }
        isMouseDownOnGrid = false;
        gridResizeSourceId = null;
        enableGridSelection("trk-grid-0");
        document.body.style.cursor = 'default';
    }

	/**
	 * Handling mouse moved on the document (outside grid), this helps in dragging work properly 
	 * though the user cursor is not in the grid area and resize accordingly
	 */		
    function mouseMovedOnDocument(event) {
        //alert("my mouse move");
        mouseMove(event);
    }

	/**
	 * Handling mouse move for grid height resize and column resize
	 *	COMMENTED THIS AS WE DO NOT NEED THIS FOR NOW	
	 *   function mouseMovedOnGrid(event) {
	 *       mouseMove(event);
	 *   }
	 */

	/**
	 * Adding listeners for mouse up and mouse move events
	 */		
    function addListeners() {
        $(document).bind("mouseup", mouseUpOnDocument);
        $(document).bind("mousemove", mouseMovedOnDocument);
    }

	/**
	 * Binding events for mouse move, used for mouse move on grid area
	 */		
    function bindEvents() {
        //$("trk-grid-0").bind("mousemove", mouseMove);
    }
    
    //Public declarations    
    var TrackingGrid = window.TrackingGrid = function() {};

    TrackingGrid.mouseMove = mouseMove;
    TrackingGrid.mouseDown = mouseDown;
    TrackingGrid.mouseUp = mouseUp;

    TrackingGrid.setAbsoluteWidth = setAbsoluteWidth;
    TrackingGrid.adjustResizer = adjustResizer;
    TrackingGrid.enableGridSelection = enableGridSelection;
    TrackingGrid.addListeners = addListeners;
    TrackingGrid.bindEvents = bindEvents;
    
})();

