/*
 * Dispatch Pages
 */
var globaliframe, imageName, ajaxResponse;

function indexPage(){
    $('#areasearch').focus(function(){
        $(this).val('');
    }).blur(function(){
        if ($(this).val() == '') {
            $(this).val('Enter a Town...');
        }
    });
    $('#areabutton').hover(function(){
        $(this).attr('src', '/images/searchbutton_hover.png');
    }, function(){
        $(this).attr('src', '/images/searchbutton.png');
    });
    loginBox();

    $("#mycarousel").jcarousel({
        wrap: 'circular',
        scroll: 1,
        auto: 8,
        animation: 300,
        easing: 'linear'
    }); 
}

function photoRegister(){
    loginBox();
    var validator = $('#photo-register').validate({
        rules: {
            captcha: {
                required: true,
                remote: {
                    url: "check-captcha.php"
                }
            }
        },
        invalidHandler: function(){
            $('#error-results').html('<p  class="error s"> There are ' + validator.numberOfInvalids() + ' errors. Please complete all fields, including a valid email.</p>');
        }
    });
}

function editVisitor(){
    loginBox();
    $('.date-input').datepicker({
        dateFormat: 'dd-mm-yy'
    });
    var validator = $('#register-visitor-form').validate({
        invalidHandler: function(){
            $('#error-results').html('<p> There are ' + validator.numberOfInvalids() + ' errors. Please complete all fields, including a valid email.</p>');
        }
    });
    $('#region').change(function(){
        $.get('getareas.php', {
            areaid: this.value
        }, function(data){
            if (data != 0) {
                $('#county').html(data);
            }
            else {
                $('#county').html('<option>--- Select County ---</option>');
            }
        });
    });
    if ($('#region').val()) {
        $.get('getareas.php', {
            areaid: $('#region').val()
        }, function(data){
            if (data != 0) {
                $('#county').html(data);
                if (county) {
                    $('#county option[value=' + county + ']').attr('selected', 'selected');
                }
            }
            else {
                $('#county').html('<option>--- Select County ---</option>');
            }
        });
    }
}

function visitorRegister(){
    loginBox();
    $('.date-input').datepicker({
        dateFormat: 'dd-mm-yy'
    });
    var validator = $('#register-visitor-form').validate({
        rules: {
            captcha: {
                required: true,
                remote: {
                    url: "check-captcha.php"
                }
            }
        },
        invalidHandler: function(){
            $('#error-results').html('<div class="error s">There are ' + validator.numberOfInvalids() + ' errors. Please complete all fields, including a valid email.</div>');
        }
    });
    $('#region').change(function(){
        $.get('getareas.php', {
            areaid: this.value
        }, function(data){
            if (data != 0) {
                $('#county').html(data);
            }
            else {
                $('#county').html('<option>--- Select County ---</option>');
            }
        });
    });
    if ($('#region').val()) {
        $.get('getareas.php', {
            areaid: $('#region').val()
        }, function(data){
            if (data != 0) {
                $('#county').html(data);
                if (county) {
                    $('#county option[value=' + county + ']').attr('selected', 'selected');
                }
            }
            else {
                $('#county').html('<option>--- Select County ---</option>');
            }
        });
    }
}

function profilePage(){
    $('#profile-thumbs a').click(function(event){
        event.preventDefault();
        var currentImage = $(this).children('img').attr('src');
        currentImage = currentImage.split('/');
        $('#profile-large-image').attr('src', '/files/upload/' + currentImage[3]);
        var largeimage = new Image();
        $(largeimage).load(function(){
            $('#profile-large-image').css({
                'max-width': '346px',
                'max-height': '240px'
            });
            $('#profile-large-image').attr('src', this.src);
        }).error(function(){
            $('#profile-large-image').css({
                'max-height': '133px',
                'max-width': '200px'
            });
        }).attr('src', '/files/upload/large_' + currentImage[3]);
    });
    $('#contact-form').submit(function(event){
        var success = $('#contact-form').validate({
            rules: {
                captcha: {
                    required: true,
                    remote: {
                        url: "/files/check-captcha.php"
                    }
                }
            }
        }).form();
        
        if (success) {
            if ($('#form-password').css('display') == "block" && !skippassword && !loggedin) {
                //Check Passwords & Let the form submit
                if (($('#contact-form input[name=password]').val() != $('#contact-form input[name=cpassword]').val()) || $('#contact-form input[name=password]').val() == '') {
                    event.preventDefault();
                    $('#contact-form input[name=cpassword]').after('<div class="error s">Passwords do not match.</div>');
                }
                
            }
            else 
                if (skippassword || loggedin) {
                //just submit
                }
                else {
                    event.preventDefault();
                    $('#form-password').slideDown();
                }
        }
        else {
            event.preventDefault();
        }
    });
    
    $('#show-all-areas').toggle(function(){
        $('#areas-rest').show();
        $('#show-all-areas').html('[Hide All]');
    }, function(){
        $('#areas-rest').hide();
        $('#show-all-areas').html('[Show All]');
    });
    
    $('#skip-register').click(function(){
        skippassword = true;
        $('#contact-form').submit();
    });
    
    $('#date-input').datepicker({
        dateFormat: 'dd-mm-yy'
    });
    loginBox();
}

function morePhotographers(){
    loginBox();
    $('#details-show-more').toggle(function(){
        $('#profile-form-container').slideDown();
    }, function(){
        $('#profile-form-container').slideUp();
    });
    $('#contact-form').validate();
    $('#update-result').animate({
        opacity: 1.0
    }, 4000).fadeOut();
    $(".date-input").datepicker({
        dateFormat: 'dd-mm-yy'
    });
}

function searchPage(){
    $('#areasearch').focus(function(){
        $(this).val('');
    }).blur(function(){
        if ($(this).val() == '') {
            $(this).val('Enter a Town...');
        }
    });
    loginBox();
}

function areaPage(){
    loginBox();
}

function loginPage(){
    loginBox();
}

function profileEdit(){
    loginBox();
    $('form .success').animate({
        opacity: 1.0
    }, 4000).slideUp();
    var validator = $('#profile-details').validate({
        invalidHandler: function(){
            $('#detail-error').remove();
            $('#profile-details').before('<div class="error s" id="detail-error">There are ' + validator.numberOfInvalids() + ' errors. Please complete all fields, including a valid email.</div>');
        }
    });
    var validator1 = $('#edit-profile').validate({
        invalidHandler: function(){
            $('#profile-error').remove();
            $('#edit-profile').before('<div class="error s" id="profile-error">There are ' + validator1.numberOfInvalids() + ' errors. Please complete all fields.</div>');
        }
    });
    $('#tachar').val(500 - $('#profile_text').val().length);
    $('#profile_text').keyup(function(){
        limitText(this, $('#tachar'), 500);
    });
    $('#profile_text').blur(function(){
        limitText(this, $('#tachar'), 500);
    });
    $('#profile-image-table').hide();
    $('.profile-image-upload').attr('disabled', 'disabled');
    $('#profile-images').sortable({
        handle: '.drag',
        revert: true,
        stop: function(event, ui){
            imageSort();
        }
    });
    //there must be a better way.
    new AjaxUpload($('#imageupload_1 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 1
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 1);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 1);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 1);
        }
    });
    
    
    
    
    
    new AjaxUpload($('#imageupload_2 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 2
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 2);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 2);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 2);
        }
    });
    new AjaxUpload($('#imageupload_3 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 3
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 3);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 3);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 3);
        }
    });
    new AjaxUpload($('#imageupload_4 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 4
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 4);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 4);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 4);
        }
    });
    new AjaxUpload($('#imageupload_5 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 5
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 5);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 5);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 5);
        }
    });
    new AjaxUpload($('#imageupload_6 .upload'), {
        action: '/account/image-upload.php',
        name: 'profile-image',
        data: {
            imageno: 6
        },
        autoSubmit: true,
        responseType: false,
        onChange: function(file, extension){
            imageUploadChange(file, extension, 6);
        },
        onSubmit: function(file, extension){
            imageUploadSubmit(file, extension, 6);
        },
        onComplete: function(file, response){
            imageUploadComplete(file, response, 6);
        }
    });
    $('.delete').click(function(){
        var el = $(this);
        var imageName = $(this).attr('rel');
        $.post('/account/image-delete.php', {
            'image': imageName
        }, function(data){
            if (data) {
                $(el).parent().siblings('img').hide();
            }
        });
        //var deleteImage = confirm('Do you want to delete this image');
    
    });
    $('#previewListing').click(function(){
        $('.photographer h3').html($('#bname').val());
        $('.photographer .phone').html('<strong>Phone:</strong> ' + $('#telephone').val());
        $('.photographer .address').html('<strong>Address:</strong> ' + $('#address').val());
        $('.photographer .website').html('<a class="external" target="_blank" href="http://' + $('#website').val() + '">' + $('#website').val() + '</a>');
        $('.photographer .about p').html($('#profile_text').val());
        $('.photographer .photo img').attr('src', $('#imageupload_1 img').attr('src'));
        $('#previewlistingview').dialog({
            modal: true,
            width: 972,
            height: 360,
            resizable: false,
            buttons: {
                Ok: function(){
                    $(this).dialog('close');
                }
            }
        });
    });
}

function limitText(limitField, limitCount, limitNum){
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    else {
        limitCount.val(limitNum - limitField.value.length);
    }
}

function renewListingPage(){
    loginBox();
    $('input[type=checkbox]').change(function(){
        calculatePrice();
    });
}

function lastMinutePage(){
    loginBox();
    $('#date').datepicker({
        dateFormat: 'dd-mm-yy',
        maxDate: '+2M'
    });
    $('#register-visitor-form').validate();
}

function lastMinuteAdminPage(){

    loginBox();
    $('.lastmincal td').click(function(){
        var c = $(this).attr('class');
        if (!c) {
            var t = $(this).attr('rel');
            var el = this;
            $.post('ajaxcal.php', {
                add: t
            }, function(data){
                if (data == 'done') {
                    $(el).addClass('free');
                };
                            });
        }
        else if (c == 'free') {
                var t = $(this).attr('rel');
                var el = this;
                $.post('ajaxcal.php', {
                    del: t
                }, function(data){
                    if (data == 'done') {
                        $(el).removeClass('free');
                    };
                });
            }
            else if (c == 'free notlastmin') {
                alert('As you have a booked event on this date, late availability is already set.');
            }
            else if (c == 'busy') {
                    alert('You have set this date to busy, please remove from calendar admin first.');
                }
    });
}

function myAccountPage(){
    loginBox();
    $('.delbutton').click(function(){
        var con = confirm('Delete This Listing?\nPlease Be Aware, this action is not reversible.\nClick OK To Delete.');
        if (!con) 
            return false;
    });
}

function visitorAccountPage(){
    loginBox();
    $('.delete a').click(function(){
        var con = confirm('Delete This Enquiry?\nClick OK To Delete');
        if (!con) 
            return false;
    });
}

/*
 * Functions
 */
function loginBox(){
    $('#sign-in').tabs();
}

function imageUploadChange(file, extension, imageno){
    $('#imageupload_' + imageno + ' .image-progress').html('Uploading...').show();
}

function imageUploadSubmit(file, extension, imageno){
    $('#imageupload_' + imageno + ' .image-progress').html('Uploading...').show();
}

function imageUploadComplete(file, response, imageno){
    ajaxResponse = eval('(' + response + ')');
    if (ajaxResponse.error) {
        $('#imageupload_' + imageno + ' .image-progress').html('ERROR').animate({
            opacity: 1.0
        }, 4000).hide(1000);
        $('#imageupload_' + imageno).css({
            border: '4px solid #FF0000',
            height: '94px',
            width: '146px'
        });
        $('#imageupload_' + imageno).animate({
            opacity: 1.0
        }, 4500, function(){
            $(this).css({
                border: '1px solid #BBBBBB',
                height: '100px',
                width: '152px'
            });
        });
        $('#uploaderrors').hide();
        $('#uploaderrors').addClass('error s ct');
        $('#uploaderrors').html(ajaxResponse.response);
        $('#uploaderrors').show();
        return;
    }
    $('#imageupload_' + imageno).css({
        border: '1px solid #BBBBBB',
        height: '100px',
        width: '152px'
    });
    $('#imageupload_' + imageno + ' .image-progress').html('COMPLETE').animate({
        opacity: 1.0
    }, 4000).hide(1000);
    $('#imageupload_' + imageno + ' img').attr('src', '/files/upload/' + ajaxResponse.response + '?ran=' + Math.random()).show();
    $('#imageupload_' + imageno + ' .delete').show();
    $('#imageupload_' + imageno + ' .drag').show();
    $('#uploaderrors').hide();
}

function imageSort(){
    var order = $('#profile-images').sortable('serialize');
    if (order !== 'undefined') {
        $.post('image-sort.php', {
            'order': order
        }, function(data){
            var counter = 1;
            $('#profile-images li').each(function(index){
                $(this).attr('id', 'imageupload_' + counter);
                $(this).find('.upload').attr('id', 'i' + counter);
                $(this).find('.delete').attr('rel', counter);
                counter++;
            });
        });
    }
}

function calculatePrice(){
    var checked, totalprice, tD;
    checked = $('input[type=checkbox]:checked').length;
    if (checked > 1) {
        tD = (((checked - 2) * increment) + mindiscount);
        
        if(tD > maxdiscount) tD = maxdiscount;
        if(tD < mindiscount) tD = mindiscount;

        totalprice = (areaprice * checked) * (1 - tD/100);
        $('#current-price').html(totalprice.toFixed(2));
        $('#discount-perc').html(tD);
    }
    else {
        $('#current-price').html((areaprice * checked).toFixed(2));
        $('#discount-perc').html('0');
    }
}


function showAreas(e){
    if (!e) 
        var e = window.event;
    e.cancelBubble = true;
    e.returnValue = false;
    
    var srcEl, newtext, areabox;
    if (e.srcElement) 
        srcEl = e.srcElement;
    if (e.target) 
        srcEl = e.target;
    newtext = '<div style="border-bottom:1px solid #999; margin:0 0 4px 0"><strong style="font-family:Arial,Helvetica,sans-serif;font-size:13px;">' + srcEl.alt + '</strong> <span style="font-size:10px">(<a href="../files/search_result.php?type_listing=' + areaArray[srcEl.alt]['dummy'] + '" style="color:#000">View All</a>)</span></div>';
    for (x in areaArray[srcEl.alt]['subareas']) {
        newtext += '<a href="../files/search_sub_result.php?type_listing=' + x + '">' + x + '</a><br />';
    }
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    }
    else 
        if (e.clientX || e.clientY) {
            posx = e.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
        }
    areabox = document.getElementById('areabox');
    areabox.innerHTML = newtext;
    
    areabox.style.display = 'block';
    areabox.style.position = 'absolute';
    areabox.style.top = posy - 20 + 'px';
    var boxwidth = areabox.offsetWidth;
    areabox.style.left = posx - (boxwidth - boxwidth / 3) - 152 + 'px';
    return false;
}

function removeArea(e){
    document.getElementById('areabox').style.display = 'none';
}

function blogPage() {
    $('.delete-post').click(function(event){
        var conf = confirm("Do you wish to delete this post?\n\nPress OK to delete or cancel to exit.");
        if(!conf) event.preventDefault();
    });
    
    $('.alert').animate({opacity: 1.0}, 4000).fadeOut();
    $('#newblog').hide();
    $('#blog-toggle').toggle(
    function(){
        $(this).text('Hide New Post Form');
        $('#newblog').slideDown();
    },
    function(){
        $(this).text('Create New Post');
        $('#newblog').slideUp();
    });
    $('#blog-title').focus(function(){
        if($('#blog-title').val() == 'Enter Post Title...'){
           $('#blog-title').val('');  
           }
    });
    $('#blog-title').blur(function(){
        if($('#blog-title').val() == '') {
            $('#blog-title').val('Enter Post Title...');
        }
    });
    $('#blog-content').focus(function(){
        if($('#blog-content').val() == 'Enter Content...'){
           $('#blog-content').val('');  
           }
    });
    $('#blog-content').blur(function(){
        if($('#blog-content').val() == '') {
            $('#blog-content').val('Enter Content...');
        }
    });
    $('#blog-form').submit(function(event){
            
            if($('#blog-title').val() == '') {
                $('#blog-title').css({border:'1px solid red'});
                alert('Post title cannot be blank.');
                event.preventDefault();
            }
            
            if($('#blog-content').val() == '') {
                $('#blog-content').css({border:'1px solid red'});
                alert('Post content cannot be blank.');
                event.preventDefault();
            }
        });
        $('#blog-content').keyup(function(){checkChars();})
        .blur(function(){checkChars();})
        .focus(function(){checkChars();})
        .change(function(){checkChars();});
}

function blogPageEdit(){
    $('.alert').animate({opacity: 1.0}, 4000).fadeOut();
    $('#blog-title').focus(function(){
        if($('#blog-title').val() == 'Enter Post Title...'){
           $('#blog-title').val('');  
           }
    });
    $('#blog-title').blur(function(){
        if($('#blog-title').val() == '') {
            $('#blog-title').val('Enter Post Title...');
        }
    });
    $('#blog-content').focus(function(){
        if($('#blog-content').val() == 'Enter Content...'){
           $('#blog-content').val('');  
           }
    });
    $('#blog-content').blur(function(){
        if($('#blog-content').val() == '') {
            $('#blog-content').val('Enter Content...');
        }
    });
    $('#blog-form').submit(function(event){
        if($('#blog-title').val() == '') {
            $('#blog-title').css({border:'1px solid red'});
            alert('Post title cannot be blank.');
            event.preventDefault();
        }
        
        if($('#blog-content').val() == '') {
            $('#blog-content').css({border:'1px solid red'});
            alert('Post content cannot be blank.');
            event.preventDefault();
        }
    });
    $('#blog-preview').click(function(event){
        event.preventDefault();
        var postid = $(this).attr('rel');
        postid = postid.slice(5);
        window.open('/account/blog_preview.php?post='+postid, 'preview',
        'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=1000,height=600');
        });
        checkChars();
        $('#blog-content').keyup(function(){checkChars();})
        .blur(function(){checkChars();})
        .focus(function(){checkChars();})
        .change(function(){checkChars();});
    }

function checkChars()
{
    var l = $('#blog-content').val().length;
    $('#char-counter').val(l);
    if (l >= 3000) {
        $('#char-counter').css({
            border: '1px solid #ff0000',
            color: '#ff0000'
        });
    }
    else 
        if (l >= 2950) {
            $('#char-counter').css({
                border: '1px solid #FF7D40',
                color: '#FF7D40'
            })
        }
        else {
            $('#char-counter').css({
                border: '1px solid #646464',
                color: '#646464'
            })
        }
}

