String.prototype.format = function() {
    var formatted = this;
    for(arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

var mobile = function(){
	return {
		detect:function(){
			var uagent = navigator.userAgent.toLowerCase(); 
			var list = this.mobiles;
			var ismobile = false;
			for(var d=0;d<list.length;d+=1){
				if(uagent.indexOf(list[d])!=-1){
					ismobile = true;
				}
			}
			return ismobile;
		},
		mobiles:[
			"midp","240x320","blackberry","netfront","nokia","panasonic",
			"portalmmm","sharp","sie-","sonyericsson","symbian",
			"windows ce","benq","mda","mot-","opera mini",
			"philips","pocket pc","sagem","samsung","sda",
			"sgh-","vodafone","xda","palm","iphone",
			"ipod","android", "playbook"
		]
	};
}();

$().ready(function () {
    images_folder = 'images';
    // global variable for the dialog name
    dialog = "";

    // the "stack" of size 1
    dialogstack = new Array();
    
    // items used
    items = {};
    
    // is it an iPad?
    var is_mobile = mobile.detect();
    
    anim_delay = 150;
    
    // open dialog code, doesn't use global
    var opendialog = function(whichdialog) {
        if (whichdialog === undefined) {
            return;
        }
        
        dialog = whichdialog;
        
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
        
        if ($(whichdialog).hasClass('simple')) {
            
            if (is_mobile) {
                $(whichdialog).css({'width':winW/2, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
                
            } else {        
                $(whichdialog).css({'width':winW/2, 'height':3*winH/4, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
                $(whichdialog).children('.innercontent').css({'height':innerh});
            }
            
            if ($(whichdialog).hasClass('setwidth'))
            {
            	var w = $(whichdialog).attr('dialogwidth');
            	$(whichdialog).css({'width':w, 'left':(winW - w) /2});
            }
            
            if ($(whichdialog).hasClass('setHeight'))
            {
            	var h = $(whichdialog).attr('dialogheight');
            	$(whichdialog).css({'height': h, 'top': (winH - h)/2+$(window).scrollTop()});
                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 35;
                $(whichdialog).children('.innercontent').css({'height':innerh});
            }
        
        } else if ($(whichdialog).hasClass('smallsimple')) {
        
            $(whichdialog).css({'width':winW/3, 'height':winH/3, 'top':winH/4   +$(window).scrollTop(), 'left':winW/3});
            
            var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
            $(whichdialog).children('.innercontent').css({'height':innerh});
        
        } else if ($(whichdialog).hasClass('setwidth')) {
            var w = $(whichdialog).attr('dialogwidth');
            $(whichdialog).css({'width':w, 'top':winH/6+$(window).scrollTop(), 'left':winW/4});
        }
        else if ($(whichdialog).hasClass('forgotpw')) {
        
            //$(whichdialog).css({'width':600, 'height': winH/3, 'top':winH/3 +$(window).scrollTop(), 'left':(winW - 600)/2});
             //$(whichdialog).css({'width':winW/2, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
            $(whichdialog).css({'width':winW/2, 'height':3*winH/4, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
                $(whichdialog).children('.innercontent').css({'height':innerh});
            
            //var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
            //$(whichdialog).children('.innercontent').css({'height':innerh});
            //$(whichdialog).children('.innercontent').css({'height':200});
        
        }
        
        if ($(whichdialog).hasClass('bottombuttons')) {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
        }
        
        // details of whichdialog loading
        // progress whichdialog, first time loading
        if (whichdialog == '#progressindicator') {
            
            var currarrow = $('#arrows .selected').attr('status');    
    
            if (currarrow == 'incomplete') {
            
                $('#pendingreasons').css('display','none');
                $('#savecancelbottombuttons').css('display','none');
                
                $('#completeddetails').css('display','none');
                
            } else if (currarrow == 'pending') {

                $('#pendingreasons').css('display','block');
                $('#savecancelbottombuttons').css('display','block');
                
                $('#completeddetails').css('display','none');
                
            } else if (currarrow == 'complete') {
                $('#pendingreasons').css('display','none');
                $('#savecancelbottombuttons').css('display','none');
                
                $('#completeddetails').css('display','block');
                $('#savecancelbottombuttons').css('display','block');
                inventorylistsize_modal();
            }
            
            formatprogressdialog();
            
            
        } else if (whichdialog == '#addinventory') {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            
            populateinventorylist();
            
        } else if (whichdialog == '#apartmentlist') {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            
        } else if (whichdialog == '#buildinglist') {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            
            populateBuildingList();
            
        } 
        
        $(whichdialog).fadeIn(anim_delay);
        
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        
        $('#mask').css({'width':maskWidth,'height':maskHeight,'top':0, 'left':0});
        $('#mask').fadeTo(anim_delay,0.2);
        
        // ADDED 22 NOV, EDITED 25 NOV, EDITED 2 DEC for '.textfields'
        $(whichdialog + ' input.roundedinput.fullwidth').each(function () {
            if ($(this).attr('padded') == 'yes') {
                return;
            }
            var label = $(this).attr('label');
            if (label == undefined) {
                return;
            }
            
            var w = parseInt($(label).width())+20;
            $(this).css('padding-left',w);
            $(this).css('width','-='+w);
            $(this).attr('padded','yes');
        
        });
        
        $(whichdialog + ' textarea.roundedinput.fullwidth').each(function () {
            if ($(this).attr('padded') == 'yes') {
                return;
            }
            var label = $(this).attr('label');
            if (label == undefined) {
                return;
            }
            
            var h = parseInt($(label).height())+30;
            $(this).css('padding-top',h);
            $(this).attr('padded','yes');
        });
        
        $(whichdialog).css('top',winH/9+$(window).scrollTop());
        
        
        if (whichdialog == '#editemployee') {
            if ($(whichdialog).children('.innercontent').attr('addedheight') != 'yes') {
                $(whichdialog).children('.innercontent').css('height', '+='+15);
                $(whichdialog).children('.innercontent').attr('addedheight','yes');
            }
        }
        
        inventorylistsize_modal();
    }
    
    // popping up a dialog for all elements with a dialog attribute
    $('[dialog]').each(function () {
        $(this).click(function () {
        
            // knows which one to pop up with the dialog="#dialogname" attr
            dialog = $(this).attr('dialog');
            opendialog(dialog);
            
        });
        
    });
    
    var resetuploaddialog = function () {
        $('#upload_attachment_button').show(100);
        $('#upload_close').hide(100);
        $('#upload_complete').hide(100);
    }
    
    // closing the dialog
    var closedialog = function(d) {
        if (d === undefined) {
            d = '';
        }
        
        if (dialog == '#uploadattachment') {
            resetuploaddialog();
        }
        
        if (dialog != '') {
        
            $(dialog).delay(d).fadeOut(anim_delay);
            dialog = '';
            if (dialogstack.length > 0) {
                dialog = dialogstack.pop();
                opendialog(dialog);
                
            } else {
                $('#mask').delay(d).fadeOut(anim_delay, function () {
                    if (dialog != '') {
                        $('#mask').fadeTo(anim_delay,0.2);
                    }
                });
            }
            
            
        }
        
    }
    
    
    alertdialog = function(title, msg) {
        $('#alerttitle').html(title);
        $('#alerttext').html(msg);
        opendialog('#alertdialog');
    }
    

    
    $('a[function="close"]').click(closedialog);
    $('#mask').click(closedialog);
    
    $('a[function="save"]').click(closedialog);
    $('a[function="cancel"]').click(closedialog);
    
       
    // so you can only select one item from the divs that have
    // the class "singleselect"
    $('div.singleselect a.listitem').click(function () {
        $(this).closest('.innercontent').children('.listitem').removeClass('selected');
        $(this).addClass('selected');
    });
    
    $(window).keydown(function (event){ 
        if (event.which == 27) {
            closedialog();
        }
    });
    
    // closes the dialog once you selected something
    $('div.closeonselect a.listitem').click(function () {
        closedialog(150);
    });
    
        
    // I apologize for the mess of the stack.
    // dialog is the current dialog open
    // the stack represents what's gonna be opened after
    // the current dialog closes
    var pushDialog = function(whichdialog) {
        if (dialog == '') {
            opendialog(whichdialog);
        } else {
            dialogstack.push(whichdialog);
        }
    }
});