setShadowBox();
var map = null;
var geocoder = null;
var tabs = null;


$(document).ready(docLoad);

function docLoad()
{
    initShadowBox();
    initTabs();
    initExample();
    initInfo();
    initUploadify();
    initUploadifyMyProvider();
    initDatePicker();
    initValidatePublish();
    initValidateRegister();
    initValidateComplete();
    initValidateQuote();
    initValidateQuestion();
    initValidateDefinition();
    initValidateVisit();
    initValidateNewAdminUser();
    initShowPhone();
}

function setShadowBox()
{
    try
    {
        Shadowbox.loadSkin('classic', path + '/resources/lib/shadowbox/skin');
        Shadowbox.loadLanguage('es', path + '/resources/lib/shadowbox/lang');
        Shadowbox.loadPlayer(['img', 'html'], path + '/resources/lib/shadowbox/player');
    }
    catch(err){}
}

function initShadowBox()
{
    try
    {
        Shadowbox.init();
    }
    catch(err){}
}

function initTabs()
{
    try
    {
        tabs = $('#tabs ul').tabs();
        $('#qa_tabs ul').tabs();
        $('#services_tabs ul').tabs();
    }
    catch(err){}
}

function initExample()
{
    try
    {
        $('.example').example(function()
        {
            return $(this).attr('title');
        }, {className: 'blur'});
    }
    catch(err){}
}

function initInfo()
{
    try
    {
        $('.info').info();
    }
    catch(err){}
}

function initUploadifyMyProvider()
{
	 try
	    {
	        $('#MyUploadphotos').fileUpload(
	        {
	            'uploader': '/resources/lib/uploadify/uploader.swf',
	            'script': '/upload-photos-my-provider.php',
	            'folder': '/resources/photos/tmp',
	            'cancelImg': '/resources/lib/uploadify/cancel.png',
	            'auto': true,
	            'multi': true,
	            'buttonText': 'Elegir foto',
	            'fileDesc': 'Archivo de imagen (Máximo 1MB)',
	            'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.orf',
	            'sizeLimit': '1048576',
	            'displayData': 'percentage',
	            'scriptData':
	            {
	              'user_id': user_id
	            },
	            'onComplete': MyUpdatePhotoList,
	            'onError': function (a, b, c, d) {
	                 if (d.status == 404)
	                        alert('Could not find upload script. Use a path relative to: '+'<?php=getcwd()?>');
	                 else if (d.type === "HTTP")
	                        alert('error '+d.type+": "+d.status);
	                 else if (d.type ==="File Size")
	                        alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
	                 else
	                        alert('error '+d.type+": "+d.text);
	            }
	        });
	    }
	    catch(err){
	    }
}

function initUploadify()
{
     try
        {
            $('#uploadphotos').fileUpload(
            {
                'uploader': '/resources/lib/uploadify/uploader.swf',
                'script': '/upload-photos.php',
                'folder': '/resources/photos/tmp',
                'cancelImg': '/resources/lib/uploadify/cancel.png',
                'auto': true,
                'multi': true,
                'buttonText': 'Elegir foto',
                'fileDesc': 'Archivo de imagen (Máximo 1MB)',
                'fileExt': '*.jpg;*.jpeg;*.gif;*.png;*.orf',
                'sizeLimit': '1048576',
                'displayData': 'percentage',
                'scriptData':
                {
                  'pre_id': pre_id,
                  'service_id': service_id,
                  'user_id': user_id
                },
                'onComplete': updatePhotoList,
                'onError': function (a, b, c, d) {
	                 if (d.status == 404)
	                        alert('Could not find upload script. Use a path relative to: '+'<?php=getcwd()?>');
	                 else if (d.type === "HTTP")
	                        alert('error '+d.type+": "+d.status);
	                 else if (d.type ==="File Size")
	                        alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
	                 else
	                        alert('error '+d.type+": "+d.text);
	            }
            });
        }
        catch(err){}
}

function initDatePicker()
{
    try
    {
        $('.date-pick').datePicker(
        {
            clickInput: true
        });
    }
    catch(err){}
}

function elementExists(id)
{
    return ($('#' + id).length != 0);
}

function toggleAwProvinces()
{
    strHidden = 'Elegir provincia';
    strVisible = 'Cancelar';

    if ($('#aw-change').html() == strHidden)
    {
        $('#aw-select').css('display', 'inline');
        $('#aw-change').html(strVisible);
    }
    else if ($('#aw-change').html() == strVisible)
    {
        $('#aw-select').css('display', 'none');
        $('#aw-change').html(strHidden);
    }
}

function triggerAwProvinces()
{
    doSubmit('f_aw');
}

function writeMail(name, domain)
{
    var email = name + '@' + domain;
    document.write('<a href="mailto: ' + email + '">' + email + '</a>');
}

function doSubmit(id)
{
    $('#' + id).submit();
}

function triggerSearch()
{
    if($('#iterm').val() != '')
    {
        var strq = $('#iterm').val();
        var strqtype = '';
        switch ($('#qtype').val())
        {
            case 's':
                strqtype = 'presupuestos';
                break;
            case 'p':
                strqtype = 'profesionales';
                break;
        }
        
        $('#f_search').attr('action', path + '/busqueda/' + strqtype + '/' + strq + '/');
        doSubmit('f_search');
    }
}

function infoClose()
{
    $('#info').slideUp('fast');
}

function initValidatePublish()
{
    try
    {
        $('#f_publish').validate({
            rules:
            {
                title:
                {
                    required: true,
                    maxlength: 255
                },
                postal_code:
                {
                    required: true,
                    minlength: 5,
                    maxlength: 5,
                    number: true
                },
                limit:
                {
                    min: 1
                },
                open_quote:
                {
                    number: true,
                    min: 0,
                    max: 60000
                },
                category:
                {
                    min: 1
                },
                description:
                {
                    required: true
                }
            },
            messages:
            {
                title:
                {
                    required: '',
                    maxlength: 'Campo demasiado largo'
                },
                postal_code:
                {
                    required: '',
                    minlength: jQuery.format('Campo sin {0} dígitos'),
                    maxlength: jQuery.format('Campo sin {0} dígitos'),
                    number: 'Campo no numérico'
                },
                limit:
                {
                    min: ''
                },
                open_quote:
                {
                    number: 'Escribe sólo el número (Ej: 200)',
                    min: 'Campo demasiado pequeño',
                    max: 'Campo demasiado grande'
                },
                category:
                {
                    min: ''
                },
                description:
                {
                    required: ''
                }
            },
            submitHandler: function(form)
            {
                $('#loading_publish').show();
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateRegister()
{
    try
    {
        $('#f_register').validate({
            rules:
            {
                email:
                {
                    required: true,
                    email: true
                },
                password:
                {
                    required: true,
                    minlength: 5,
                    maxlength: 20
                },
                password2:
                {
                    required: true,
                    equalTo: '#rpassword'
                },
                username:
                {
                    required: true,
                    maxlength: 255
                }
            },
            messages:
            {
                email:
                {
                    required: 'Campo requerido',
                    email: 'Correo no válido'
                },
                password:
                {
                    required: 'Campo requerido',
                    minlength: 'Campo demasiado corto',
                    maxlength: 'Campo demasiado largo'
                },
                password2:
                {
                    required: 'Campo requerido',
                    equalTo: 'Las contraseñas no son iguales'
                },
                username:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                }
            },
            submitHandler: function(form)
            {
                if (checkSubmit())
                    form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateComplete()
{
    try
    {
        $('#f_complete').validate({
            rules:
            {
                username:
                {
                    required: true,
                    maxlength: 255
                },
                email:
                {
                    required: true,
                    email: true
                },
                phone:
                {
                    required: true,
                    maxlength: 20
                },
                name:
                {
                    required: true,
                    maxlength: 255
                },
                nifcif:
                {
                    required: true,
                    maxlength: 10
                },
                address:
                {
                    required: true
                },
                postal_code:
                {
                    required: true,
                    minlength: 5,
                    maxlength: 5
                }
            },
            messages:
            {
                email:
                {
                    required: 'Campo requerido',
                    email: 'Correo no válido'
                },
                username:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                },
                phone:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                },
                name:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                },
                nifcif:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                },
                address:
                {
                    required: 'Campo requerido'
                },
                postal_code:
                {
                    required: 'Campo requerido',
                    minlength: 'Campo demasiado corto',
                    maxlength: 'Campo demasiado largo'
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateQuote()
{
    try
    {
        $('#f_quote').validate({
            rules:
            {
                type:
                {
                    required: true
                },
                quote:
                {
                    number: true,
                    min: 0,
                    max: 60000
                },
                description:
                {
                    required: true
                }
            },
            messages:
            {
                type:
                {
                    required: '***'
                },
                quote:
                {
                    number: 'Escribe sólo el número (Ej: 200)',
                    min: 'Campo demasiado pequeño',
                    max: 'Campo demasiado grande'
                },
                description:
                {
                    required: 'Campo requerido'
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateQuestion()
{
    try
    {
        $('#f_question').validate({
            rules:
            {
                title:
                {
                    required: true
                },
                category:
                {
                    min: 1
                }
            },
            messages:
            {
                title:
                {
                    required: ''
                },
                category:
                {
                    min: ''
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateDefinition()
{
    try
    {
        $('#f_definition').validate({
            rules:
            {
                title:
                {
                    required: true
                }
            },
            messages:
            {
                title:
                {
                    required: ''
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateVisit()
{
    try
    {
        $('#f_visit').validate({
            rules:
            {
                phone:
                {
                    required: true
                },
                message:
                {
                    required: true
                },
                date:
                {
                    required: true,
                    date: true
                }
            },
            messages:
            {
                phone:
                {
                    required: 'Campo requerido'
                },
                message:
                {
                    required: 'Campo requerido'
                },
                date:
                {
                    required: 'Campo requerido',
                    date: 'Formato incorrecto'
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initValidateNewAdminUser()
{
    try
    {
        $('#f_newuser').validate({
            rules:
            {
                username:
                {
                    required: true,
                    maxlength: 255
                },
                postal_code:
                {
                    required: true,
                    minlength: 5,
                    maxlength: 5
                }
            },
            messages:
            {
                username:
                {
                    required: 'Campo requerido',
                    maxlength: 'Campo demasiado largo'
                },
                postal_code:
                {
                    required: 'Campo requerido',
                    minlength: 'Campo demasiado corto',
                    maxlength: 'Campo demasiado largo'
                }
            },
            submitHandler: function(form)
            {
                form.submit();
            },
            onkeyup: false
        });
    }
    catch(err){}
}

function initShowPhone()
{
    try
    {
        $("#d_movil_texto").click(function(){
            if ( $("#d_movil_telf").css("display") == "none" ){
                    $("#d_movil_telf").css("display","");
                    $("#d_movil_texto").css("display","none");
            };
        });
    }
    catch(err){}
}