window.ihouseu = new Object();
window.ihouseu.unserialize = function(string)
{
    var ret = new Object();
    var vars = string.split('&');
    
    for (var j=0; j<vars.length; j++)
    {
        var array = vars[j].split('=');
        ret[ihouseu.trim(array[0])] = ihouseu.trim(array[1]);
    }
    
    return ret;
}

window.ihouseu.trim = function(string)
{
    var trimmed = string.replace(/^[\t\n ]/g,'').replace(/[\t\n ]$/g,'');
    return string == trimmed ? string : ihouseu.trim(trimmed);
}

window.ihouseu.serialize = function(object)
{
    var string = "";
    for (var index in object)
        string += (string?"&":'')+index+"="+object[index];
        
    return string;
}

window.ihouseu.copy = function(object1, object2)
{
    for (var index in object2)
        object1[index] = object2[index];
}

window.ihouseu.def = function()
{
    for (var i=0; i<arguments.length; i++)
        if (arguments[i] != null && arguments[i]!="")
            return arguments[i];
}

window.ihouseu.toObject = function(string)
{
    return ihouseu.unserialize(string.replace(/[;,]/g,'&').replace(/:/g,'='));
}

window.ihouseu.alert = function(string)
{
    $("<div id='dialog' class='ihouseualert'>"+string+"</div>'").dialog({
        autoOpen: true,
        show: 'drop',
        closeText: 'x',
        hide: 'drop',
        modal: true,
        title: 'Alert',
        close: function()
        {
            $('#dialog').dialog('destroy').remove();
        }});
}

window.ihouseu.assignPopup = function(object, params, options)
{
    try
    {
        for (var i=0; i<object.length; i++)
        {
            var url = $(object[i]).attr('href');
			if(!url)
				return;

            if (url.indexOf('?')!=-1)
                object[i].url = url.split('?')[0];
            else
                object[i].url = url;
            
            object[i].data = new Object();
            if (url.indexOf('?')!=-1)
                ihouseu.copy(object[i].data,ihouseu.unserialize(url.split('?').pop()));
            
            if ($(object[i]).attr('params'))
                ihouseu.copy(object[i].data, ihouseu.toObject($(object[i]).attr('params').replace(/,/g,';')));

            if (params)
                ihouseu.copy(object[i].data, params);
            
            object[i].options = new Object();
            if ($(object[i]).attr('rel'))
                ihouseu.copy(object[i].options, ihouseu.toObject($(object[i]).attr('rel').replace(/,/g,';')));

            if (options)
                ihouseu.copy(object[i].options, options);
            
            $(object[i]).attr('href','#').removeAttr('params').removeAttr('rel');//.removeClass('displayPopup');            
            
            $(object[i]).unbind('click').click(function(ev)
            {
                ev.preventDefault();
                ihouseu.displayPopup(this.url, this.data, this.options);
            });
        }
    }
    catch(e)
    {
        ihouseu.alert(e);
    }
}

window.ihouseu.popup = {active: false, form: null, data: {}}
window.ihouseu.displayPopup = function(url, params, options)
{    
     //if (window.ihouseu.popup.active == true)
        //return;
        
     if (!params)
        params = new Object();

     if (!options)
        options = new Object();

     if (options.onbeforeopen)
         options.onbeforeopen();
         
     if ($('#dialog').dialog)
        $('#dialog').dialog('close');

     params.popup = true;
     
     window.ihouseu.popup.active = true;
     $.ajax({
         url: url,
         type: 'GET',
         dataType: 'html',
         data: ihouseu.serialize(params),
         success: function(response){
             var html = null;
             window.ihouseu.popup.active = false;
             
             if (response)
                 switch(response)
                 {
                     case 'permission_denied': 
                     case 'session_timeout':
                     default: html = response;
                 }
             else
                html = "No response";
                
             var buffer = document.createElement('span');
             buffer.innerHTML = html;
             
             var form = $(buffer).find('form');
             if (form.length > 0)
             {
                window.ihouseu.popup.form = form;

                form.append("<input type='hidden' value='true' name='popup'/>");
                if (options.onsubmit)
                    form.onaftersubmit = options.onsubmit;
             }
             
             var title = $(buffer).find('h1:first, h2:first, h3:first')[0];
             var title_val = "";
             
             if (title)
             {
                title_val = $(title).html();
                $(title).remove();
             }
             
             html = buffer.innerHTML;                    
             
             $("<div id='dialog' style='background: #ffffff'>"+html+"</div>'").dialog({
                    autoOpen: true,
                    show: 'drop',
                    closeText: 'x',
                    hide: 'drop',
                    modal: true,
                    title: "<span class='logo'></span>" + "<span class='popUpTitle'> | &nbsp;&nbsp;"+(options.title == false || options.title == "false" ? null : title_val)+"</span>",
                    width:  options && ihouseu.def(options.w, options.width) ? parseInt(ihouseu.def(options.w, options.width)) : 'auto',
                    height: options && ihouseu.def(options.h, options.height) ? parseInt(ihouseu.def(options.h, options.height)) : 'auto',
                    beforeclose: function()
                    {
                      if (options.onbeforeclose)
                        options.onbeforeclose();  
                    },
                    close: function()
                    {
                        if ($('#dialog').dialog)
                        {
                            $('#dialog *').remove();
                            $('#dialog').dialog('destroy').remove();

                            if (options.onclose)
                                options.onclose();
                        }
                    },
                    open: function()
                    {
                        // to make sure that the popup is open
                        window.setTimeout(function()
                        {
                            $("#dialog").html(html);
                            ihouseu.assignPopup($("#dialog .displayPopup"));
                            
                            if ($("#dialog form").attr('redirect'))
                            {
                                $("#dialog form").attr('action', $("#dialog form").attr('redirect')).removeAttr('redirect');
                            }
                            
                            $("#dialog form").submit(function(ev)
                            {
                                ihouseu.ajaxValidate(this, ev, (options.type ? options.type : null));
                            });
                            
                            if (options.onopen)
                                options.onopen();
                        },500);
                    }
                });
         }
    });
}

ihouseu.ajaxValidate = function(obj, ev, type)
{    
    if (ev.preventDefault)
        ev.preventDefault();
    
    var params = new Object();    
    $(obj).find("[name]").each(function()
    {
        if (!$(this).attr('disabled'))
            params[$(this).attr('name')] = $(this).val();
    });
    
    var url = String($(obj).attr('action') ? $(obj).attr('action') : window.location);

    $.ajax({
        url: url.substring(0, url.indexOf('#') != -1 ? url.indexOf('#') : url.length),
        data: params,
        type: "POST",
        dataType: 'json',
        success: function(data)
        {            
            $(obj).find('input, textarea, select').each(function()
            {
                if ($(this).hasClass('error_red'))
                {
                    $(this).removeClass('error_red');
                    $(this).next().remove();
                }
            });

            if (data.error == 1)
                for (var index in data)
                {
                    var msg = new Array();
                    var sug = new Array();
                    
                    for (var error in data[index])
                    {
                        if (error != '__suggestion') 
                            msg.push(data[index][error]);
                        else
                            sug.push(data[index][error]);
                    }    
                    
                    $(obj).find('input[name='+index+'], textarea[name='+index+'], select[name='+index+']').each(function()
                    {
                        $(this).addClass('error_red').after('<p class="error err">* '+msg.join(", ")+'</p>');
                        if (sug.length > 0)
                            $(this).val(sug.join(", "));
                    });
                }
            else
            {
                $(obj).unbind('submit');
                $(obj).find("input[name=popup]").remove();
                
                var submit = $(obj).find("[type=submit]");
                $(obj).append("<input type='hidden' name='"+submit.attr('name')+"' value='"+submit.val()+"'/>");

                if (type == 'post')
                {
                    delete params['popup'];
                    
                    $.ajax({
                        url: url.substring(0, url.indexOf('#') != -1 ? url.indexOf('#') : url.length),
                        data: params,
                        type: "POST",
                        dataType: 'json',
                        success: function(data)
                        {
                            if (window.ihouseu.popup.form.onaftersubmit)
                            {
                                window.ihouseu.popup.form.onaftersubmit(data);
                                window.ihouseu.popup.form.onaftersubmit = null;
                                
                                $('#dialog').dialog('close');
                            }
                            else
                                $(obj).submit();
                        }
                        });
                }
                else
                    $(obj).submit();
            }
        }
    })
}
