//
// DEVNET.JS - DEVNET's javascript goodie-bag.  Borrowed in some part from
//             the Krang project (http://krang.sourceforge.net).  Builds
//             on JQuery where necessary.
//

//
// Create the DEVNET namespace
//
var DEVNET;
if (typeof DEVNET == 'undefined') {
    DEVNET = {};
}

//
// CODE MANAGEMENT
//

// Run the specified code block
DEVNET.run_code = function( code_array ) {
    var size = code_array.length;
    for(var i=0; i< size; i++) {
        var code = code_array.shift();
        if( code ) code();
    }
}

// This should run when a page gets loaded.
DEVNET.load = function( target ) {
    DEVNET.loadControls();
    DEVNET.run_code( DEVNET.onload_code );
    
    Shadowbox.init();
};

// Add some code that will get executed after the DOM is loaded.  Multiple
// calls will not overwrite previous calls and all code will be executed
// in the order given.
DEVNET.onload_code = [];
DEVNET.onload = function( code ) {
    DEVNET.onload_code.push( code );
};

// Set up whatever controls we need on this page
DEVNET.loadControls = function() {
    jQuery(function($){
        $("#house_number_low").livequery(function(){
        	$(this).mask( "9?9999" );
        });
        $("#house_number_high").livequery(function(){
        	$(this).mask( "9?9999" );
        });
        $("#sale_date_low").livequery(function(){
        	$(this).mask( "99/99/9999" );
        });
        $("#sale_date_high").livequery(function(){
        	$(this).mask( "99/99/9999" );
        });
        $("#sale_price_low").livequery(function(){
        	$(this).mask( "$9?99999999" );
        });
        $("#sale_price_high").livequery(function(){
        	$(this).mask( "$9?99999999" );
        });
        $("#sq_ft_low").livequery(function(){
        	$(this).mask( "9?999999" );
        });
        $("#sq_ft_high").livequery(function(){
        	$(this).mask( "9?999999" );
        });
        $("#year_built_low").livequery(function(){
        	$(this).mask( "9999" );
        });
        $("#year_built_high").livequery(function(){
        	$(this).mask( "9999" );
        });
    });

    $.extend(DateInput.DEFAULT_OPTS, {
        stringToDate: function(string) {
            var matches;

            if (matches == string.match(/^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/)) {
                return new Date(matches[3], matches[1] - 1, matches[2]);
            }
            else {
                return null;
            };
        },
        dateToString: function(date) {
            var month = (date.getMonth() + 1).toString();
            var dom   = date.getDate().toString();

            if (month.length == 1) month = "0" + month;
            if (dom.length   == 1) dom   = "0" + dom;

            return month + "/" + dom + "/" + date.getFullYear();
        }
    });
    //$($.date_input.initialize);
	

    $(document).ready(function() {
        $('.township').livequery(function(){
        	$(this).multiselectable({
                selectableLabel: 'All Townships/Municipalities',
                selectedLabel:   'Selected'
            });
        })
        $('.neighborhood').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Neighborhoods',
	            selectedLabel:   'Selected'
	        });
        })
        $('.styles').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Styles',
	            selectedLabel:   'Selected'
	        });
        })
        $('.taxcode').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Tax Codes',
	            selectedLabel:   'Selected'
	        });
        })
        $('.taxdistrict').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Tax Districts',
	            selectedLabel:   'Selected'
	        });
        })
        $('.propuse').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Property Classes',
	            selectedLabel:   'Selected'
	        });
        })
        $('.exemption').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Exemption Types',
	            selectedLabel:   'Selected'
	        });
        })
        $('.luse').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Land Uses',
	            selectedLabel:   'Selected'
	        });
        })
        $('.nrel').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Name Relationships',
	            selectedLabel:   'Selected'
	        });
        })
        $('.owntype').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Owner Types',
	            selectedLabel:   'Selected'
	        });
        })
        $('.propclass').livequery(function(){
        	$(this).multiselectable({
	            selectableLabel: 'All Property Classes',
	            selectedLabel:   'Selected'
	        });
        })
        
        
		//DP: Call Site specific (TaxInquiry namespace) stuff here
        if (typeof TaxInquiry != 'undefined') { TaxInquiry.onready(); }
        //DP: Call Site specific Style overrides here (styles that can't be acheived with CSS, kludges, etc)
        if (typeof Style != 'undefined') { Style.onready(); }
        
    });
};

//
// COOKIE AND CONFIG MANAGEMENT
//
DEVNET.Cookie = {
    get : function( name ) {
        var value  = null;
        var cookie = document.cookie;
        var start, end;

        if ( cookie.length > 0 ) {
            start = cookie.indexOf( name + '=' );

            // if the cookie exists
            if ( start != -1 )  {
                start += name.length + 1; // need to account for the '='

                // set index of beginning of value
                end = cookie.indexOf( ';', start );

                if (end == -1) end = cookie.length;

                value = decodeURIComponent( cookie.substring( start, end ));
            }
        }
        return value;
    },
    
    set : function( name, value ) {
        document.cookie = name + '=' + encodeURIComponent( value ) + "; path=/";
    },
    
    json_get : function( name ) {
        var json = DEVNET.Cookie.get( name );
        return eval('(' + json + ')');
    }
}


// Returns a hash of preferences values from the server (passed to us via a JSON cookie)
DEVNET.prefs = function() { return DEVNET.Cookie.json_get('DEVNET_PREFS'); }

// Returns a hash of config information values from the server (passed to us via a JSON cookie)
DEVNET.config = function() { return DEVNET.Cookie.json_get('DEVNET_CONFIG'); }

//
// PAGE MANIPULATION
//

//Line up element with xguide and yguide (note that this will remove padding-left and padding-top for accuracy)
DEVNET.lineup = function(xguide, yguide, element) {
	var leftpos = $("#" + xguide + ":first").offset();
	var toppos = $("#" + yguide + ":first").offset();
	$("#" + element + ":first").css({
		"position" : "absolute",
		"top" : toppos.top + "px",
		"left" : leftpos.left + "px",
		"padding-left" : "0px",
		"padding-top" : "0px"
	});
};

//Stack a group of elements vertically starting at xguide and yguide (note that this will remove padding-left and padding-top for accuracy)
//(also note that this will not add padding between elements, add padding-bottom to your classes/id's to acheive that)
DEVNET.stack = function(xguide, yguide, elements) {
	var leftpos = $("#" + xguide + ":first").offset();
	var toppos = $("#" + yguide + ":first").offset();
	for(i = 0; i < elements.length; i++) {
		var y;
		if (i > 0) { 
			var offset = $("#" + elements[i - 1]).offset();
			y = offset.top;
			y += $("#" + elements[i - 1]).outerHeight();
		} else {
			y = toppos.top;
		}
		
		$("#" + elements[i] + ":first").css({
			"position" : "absolute",
			"top" : y + "px",
			"left" : leftpos.left + "px",
			"padding-left" : "0px",
			"padding-top" : "0px"
		});
	};
};

DEVNET.stackAllByClass = function(xguide, yguide, className) {
	var leftpos = $("#" + xguide + ":first").offset();
	var toppos = $("#" + yguide + ":first").offset();
	//get array of elements to stack based on their class
	var elements = $("." + className);
	
	for(i = 0; i < elements.length; i++) {
		var y;
		if (i > 0) { 
			var offset = $("#" + elements[i - 1].id).offset();
			y = offset.top;
			y += $("#" + elements[i - 1].id).outerHeight();
		} else {
			y = toppos.top;
		}
		
		$("#" + elements[i].id + ":first").css({
			"position" : "absolute",
			"top" : y + "px",
			"left" : leftpos.left + "px",
			"padding-left" : "0px",
			"padding-top" : "0px"
		});
	};
};


// Show, hide, or toggle a page element
DEVNET.show = function( theElement ) {
    document.getElementById(theElement).style.display = '';
}

DEVNET.showAllByClass = function(className) {
	$("." + className).each(function() {
		$(this).show();
	});
}

DEVNET.hideAllByClass = function(className) {
	$("." + className).each(function() {
		$(this).hide();
	});
}

DEVNET.hide = function( theElement ) {
    document.getElementById(theElement).style.display = 'none';
}

DEVNET.showFade = function(theElement, duration) {
	$("#" + theElement + ":first").fadeIn(duration);
}

DEVNET.showBlind = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").show("blind", { direction : animDirection }, duration);
}

DEVNET.showClip = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").show("clip", { direction : animDirection }, duration);
}

DEVNET.showDrop = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").show("drop", { direction : animDirection }, duration);
}

DEVNET.showExplode = function(theElement, pieces, duration) {
	$("#" + theElement + ":first").show("explode", { number : pieces }, duration);
}

DEVNET.showFold = function(theElement, duration) {
	$("#" + theElement + ":first").show("fold", { }, duration);
}

DEVNET.showPuff = function(theElement, duration) {
	$("#" + theElement + ":first").show("puff", { }, duration);
}

DEVNET.showSlide = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").show("slide", { direction : animDirection }, duration);
}

DEVNET.hideFade = function(theElement, duration) {
	$("#" + theElement + ":first").fadeOut(duration);
}

DEVNET.hideBlind = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").hide("blind", { direction : animDirection }, duration);
}

DEVNET.hideClip = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").hide("clip", { direction : animDirection }, duration);
}

DEVNET.hideDrop = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").hide("drop", { direction : animDirection }, duration);
}

DEVNET.hideExplode = function(theElement, pieces, duration) {
	$("#" + theElement + ":first").hide("explode", { number : pieces }, duration);
}

DEVNET.hideFold = function(theElement, duration) {
	$("#" + theElement + ":first").hide("fold", { }, duration);
}

DEVNET.hidePuff = function(theElement, duration) {
	$("#" + theElement + ":first").hide("puff", { }, duration);
}

DEVNET.hideSlide = function(theElement, animDirection, duration) {
	$("#" + theElement + ":first").hide("slide", { direction : animDirection }, duration);
}

DEVNET.toggle = function( theElement ) {
    if ( ($("#" + theElement + ":visible")).length > 0 ) {
        $("#" + theElement).hide();
        $("input:visible:text:first").focus();
    }
    else {
        $("#" + theElement).show();
        $("#" + theElement + " input:visible:first").focus();
    }
}

DEVNET.selectAll = function( arg_form, arg_element ) {
    for(var f=0; f < document.forms.length; f++)
    {
        if(document.forms[f].name == arg_form)
        {
        	for (var i=0; i < document.forms[f].elements.length; i++)
            {
        	    var e = document.forms[f].elements[i];
                if (e.name == arg_element) { e.checked = true; }
        	}
        }
	}
}

DEVNET.deselectAll = function( arg_form, arg_element ) {
    for(var f=0; f < document.forms.length; f++)
    {
        if(document.forms[f].name == arg_form)
        {
        	for (var i=0; i < document.forms[f].elements.length; i++)
            {
        	    var e = document.forms[f].elements[i];
                if (e.name == arg_element) { e.checked = false; }
        	}
        }
	}
}

DEVNET.highlight = function( row, newclass ) {
    row.className = newclass;
}

DEVNET.setFocus = function( arg_focus ) {
    document.getElementById(arg_focus).focus();
}

//animations
DEVNET.animateIt = function(theElement, effect, animProperties, duration) {
	$("#" + theElement + ":first").effect(effect, animProperties, duration);
}

DEVNET.infoAlert = function(theInfo) {
	DEVNET.showSlide(theInfo, "horizontal", 150);
	DEVNET.animateIt(theInfo, "shake", { times : 2, distance : 10 }, 150);
}

DEVNET.warningAlert = function(theWarning) {
	DEVNET.showPuff(theWarning, 850);
} 

//Triggers the proper alert function for all notice types
DEVNET.alertAll = function() {
	//get array of elements to stack based on their class
	$(".fg-info").each(function() {
		DEVNET.infoAlert(this.id);
	});
	$(".fg-warning").each(function() {
		DEVNET.warningAlert(this.id);
	});
};

// 
// APPLICATION FUNCTIONS
//
DEVNET.openStatement = function( parcelURL ) {
    var printWin = window.open( parcelURL, "Printing", 'scrollbars=yes,resizable=yes,width=800,height=600' );
}

DEVNET.printStatement = function( parcelURL ) {
    var printWin = window.open( parcelURL, "Printing", 'scrollbars=yes,resizable=yes,width=800,height=600' );
    printWin.print();
}

// Sleep for the specified number of seconds.
DEVNET.sleep = function( naptime ) {
    naptime      = naptime * 1000;
    var sleeping = true;
    var now      = new Date();
    var alarm;
    var startingMSeconds = now.getTime();
    
    while( sleeping ) {
        alarm = new Date();
        alarmMSeconds = alarm.getTime();
        if(alarmMSeconds - startingMSeconds > naptime) { sleeping = false; }
    }      
}

DEVNET.formToJSON = function( formName ) {
	return $(formName + " :input").serializeArray();
}

//lazy load a div via ajax if it doesn't yet exist. Executes optional callback if provided.
DEVNET.lazyLoad = function( template, idToLoad, parent, callback ) {
	if( ($("#" + idToLoad)).length == 0 ) {
		$.getJSON('/propertyinquiry.pl?rm=load_ajax&ajax=1&viewpage=' + template + '&', function(data){ 
			$("#" + parent).append( data.content );
			if( !(callback === undefined) ) {
				callback();
			}
		});
	} else {
		//call callback anyway if provided
		if( !(callback === undefined) ) {
			callback();
		}
	}
}

//
//LIB FUNCTIONS
//
//adds a trim() function to string objects
String.prototype.trim = function(){
	return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}

//adds a startsWith() function to string objects
String.prototype.startsWith = function(str){
	return (this.toLowerCase().match("^" + str.toLowerCase()) == str)
}

//adds an endsWith() function to string objects
String.prototype.endsWith = function(str){
	return (this.toLowerCase().match(str.toLowerCase() + "$") == str)
}

//
// DEPRECATED FUNCTIONS?
//
function ViewImage(arg_document, arg_image)
{
    // Pop up another window
    window.open(arg_image, arg_document, 'scrollbars=yes,resizable=yes,width=800,height=600');
}

function ChangeTab(tab_name)
{
    document.criteria.tab.value = tab_name;
    document.criteria.submit();
}

function OpenHelp(arg_url)
{
    lw_help = window.open(arg_url, "thewindow", "width=500,height=500,left=100,top=100,status=no,toolbar=no,menubar=no,scrollbars=yes,location=no,directories=no,resizable=no");
    lw_help.focus();
}

function ChangeTaxSale(arg_sale_id)
{
    document.criteria.sale_id.value = arg_sale_id;
    document.criteria.tab.value = "Redemption";
    document.criteria.submit();
}
