$(document).ready(function(){

    /* Date time picking */
    configure_event_for_datetime();

    /* Commenting */
    configure_event_for_commenting(); 
    configure_event_for_comment_replying();
        

    /* Photo uploading */
    var fileMax = 20;
    $('#files_list').html("<strong>Files (maximum " + fileMax + "):</strong>");

    $('#file_input').change(function(){
       add_input_element(this, fileMax);
    });
    

    /* Tagging */
    configure_event_for_tagging();

    /* Rating */ 
    load_star_for_album_thumbs();
    load_star_for_item();
    configure_event_for_rating(); 
    
    
    /* Slideshow */
    configure_event_for_slideshow();
    

    /* User control panel */
    $("#usercp_container").tabs();
    configure_event_for_user_info();
    configure_event_for_user_events();
    configure_event_for_user_albums();


    /* Admin control panel */
    $("#admincp").tabs();


    /* Form validation */
   configure_form_validation(); 


    /* Photographer login/sign-up */
    configure_event_photographer();

    /* Admin login */
    configure_event_for_admin();

    /* Search */
    configure_event_for_searching();

    var url = top.location.href;
    if(url.search(/.+photo\/(index|tagged_photos|searched_photos|adv_searched_photos)\/.+/) == -1) {
        setCookie("SCROLL_POS", 0, 1);
    }

}); /* $(document).ready() */



/***********************************************
 * Ultilities Functions
 ***********************************************/
function add_input_element(obj, fm) {

    if($('input.upload').size() > fm) {
        return true;
    }

    $(obj).hide();
    $(obj).parent().prepend('<input type="file" class="upload" name="userfile[]" />').find("input").change(function() {add_input_element(this, fm)});
    var v = obj.value;

    if(v != '') {

        $("div#files_list").append('<div>'+v+'<input type="button" class="remove" value="Remove" /></div>')
            .find("input").click(function() {
                $(this).parent().remove();
                $(obj).remove();
                return true;
            });
    }
}




function load_star_for_album_thumbs() {

    var enable = false;

    $(".album_thumb_rate").each(function() {

        var current_rate = $(this).attr("id").split("_")[0];

        $(this).ratings(5, current_rate/10, enable).bind('ratingchanged', function(event, data) {
            
        });
    });
}

function load_star_for_item() {

    $(".item_rate").each(function() {

        var ratable = $('#ratable').val();
        var already_rated = $('#already_rated').val();
        
        enable = false;
        if(already_rated == 'NO') { 
            enable = true; 
        }
        
        var star_wrapper = $(this);
        var current_rate = $(this).attr("id").split("_")[0];
        var total_ratings = $(this).attr("id").split("_")[1];
        var iid = $('#iid').val();
        var it = $('#it').val();

        $(this).ratings(5, current_rate, enable).bind('ratingchanged', function(event, data) {

            $("#rating_container span#signin_span").remove();
            $("#rating_container").append("<span id='thanks'>Thanks for rating!</span>");

            $.post('/rate/get_rate/' + it + '/' + iid, {rate: data.rating*10}, function(db) {
                //star_wrapper.empty().ratings(5, db.avg, false);     
                star_wrapper.empty().ratings(5, data.rating, false);     
            }, "json");
        });

        $('#rating_container').append($("<span id='signin_span'>" + total_ratings + " ratings</span>"));
    });

}

function configure_event_for_rating() {

    var ratable = $('#ratable').val();
    var already_rated = $('#already_rated').val();
    var num_ratings_wrapper = $('#rating_container span#signin_span');
    var thanks_wrapper = $('#rating_container span#thanks');

    if(ratable == 'NO') {
        $("#rating_container > *").mouseenter(function() {
            $('#rating_container span#signin_span').remove();
            $('#rating_container').append($("<span id='signin_span'><a href='/login'>Sign in</a> to rate.</span>")); 
        });
        $("#rating_container").mouseleave(function() {
            $('#rating_container span#signin_span').remove();
            if(!thanks_wrapper) {
                $('#rating_container').append(num_ratings_wrapper);
            }
        }); 
    }
    else if(already_rated == 'YES') {
        $("#rating_container > *").mouseenter(function() {
            $('#rating_container span#signin_span').remove();
            $('#rating_container').append($("<span id='signin_span'>You have already rated.</span>"));   
        });
        $("#rating_container").mouseleave(function() {
            $('#rating_container span#signin_span').remove();
            if(!thanks_wrapper) {
                $('#rating_container').append(num_ratings_wrapper);
            }
        }); 
    }
    else {

        $(".item_rate > div").mouseenter(function() {
            var r = $(this)[0].rating;
            var msg;
            if(r == 1) {
                msg = "Poor";
            }
            else if(r == 2) {
                msg = "Nothing special";
            }
            else if(r == 3) {
                msg = "Worth looking";
            }
            else if(r == 4) {
                msg = "Pretty cool";
            }
            else if(r == 5) {
                msg = "Awsome";
            }

            $('#rating_container span#signin_span').remove();
            $('#rating_container').append($("<span id='signin_span'>" + msg + "</span>"));
        });

        $(".item_rate > div").mouseleave(function() {
            $('#rating_container span#signin_span').remove();
            if(!thanks_wrapper) {
                $('#rating_container').append(num_ratings_wrapper);
            }
        });
    }
}


function configure_event_for_commenting() {

    var comment_limit = $("#comment_limit").val();
    var iid = $('#iid').val();
    var it = $('#it').val();

    $('#post_comment_link').click(function() {
            
        $('#comment_box > textarea').val('');
        $('#comment_box > input:first').attr('value', 'Post Comment');    
        $('#comment_box > input:last').show();
        $('#comment_box > *').attr('disabled', false);    
        $('#comment_box').slideDown();    
        return false;
    });

    $('#comment_box > input:first').click(function() {
    
        var comment_limit = $("#comment_limit").val();
        var c = $('#comment_box > textarea').val();
        if(c == '') {

            alert('You must enter a comment!');
            return;
        }

        $.post('/comment/save', {item_id: iid, item_type: it, replied_to_id: 0, comment: c}, function(data) {
            
               $('#comment_listing').load('/comment/get_comment/' + it + '/' + iid + '/' + comment_limit, function() {
                   configure_event_for_comment_replying();
               }); 
               $("dfn#num_comments").html(data);
        });

        $('#comment_box > input:first').attr('value', 'Comment Posted!');    
        $('#comment_box > input:last').hide();
        $('#comment_box > *').attr('disabled', true);    

        return false;
    });

    $('#comment_box > input:last').click(function() {
    
        $('#comment_box').slideUp();    
        return false;
    });
}

function configure_event_for_comment_replying() {

    var comment_limit = $("#comment_limit").val();
    var iid = $('#iid').val();
    var it = $('#it').val();

    $("div a.reply_to").click(function() {

        var replied_to_id = $(this).attr("id").split("_")[2];

        $('#reply_box_ > textarea').val('');
        $('#reply_box_ > input:first').attr('value', 'Post Comment');    
        $('#reply_box_ > input:last').show();
        $('#reply_box_ > *').attr('disabled', false);    
        $('#reply_box_' + replied_to_id).slideDown();

        return false;
    });

    $(".discard_post").click(function() {
    
        var replied_to_id = $(this).attr("id").split("_")[2];

        $("#reply_box_" + replied_to_id).slideUp();    
        return false;
    });

    $(".post_comment").click(function() {
        
        var replied_to_id = $(this).attr("id").split("_")[2];

        var c = $("#reply_box_" + replied_to_id + " > textarea").val();

        if(c == '') {
            alert('You must enter a comment!');
            return;
        }

        $.post("/comment/save", {item_id: iid, item_type: it, replied_to_id: replied_to_id, comment: c}, function(data) {
            $('#comment_listing').load('/comment/get_comment/' + it + '/' + iid + '/' + comment_limit, function() {
            configure_event_for_comment_replying(); 
        }); 
            $("dfn#num_comments").html(data); 
        });

        $("#reply_box_" + replied_to_id).slideUp();

        return false;
    });
}


function load_photo_rate(type, id) {

   $('#rating_container').load('/rate/load_photo_rate/' + id, function(){
   
        load_star_for_item();
        configure_event_for_rating();
    });
     
}

function load_comment(type, id) {

    $('#comment_listing').load('/comment/get_comment/' + type + '/' + id, function() {
        if($("#comment_listing > ul").children().size() > 2) {
            $("#show_more_comments").show();
        }         
        else {
            $("#show_more_comments").hide();
        }
    });
}


function load_photo_detail(type, id) {

    var current_index = $('#slideshow img.active').attr('title');
    $("dfn#current_index").html(current_index);

    //var str = window.location.href;
    //cur_url = str.split("\/");
    //var new_url = "";
    //for(var i = 0; i < cur_url.length - 1; i++) {
    //  new_url += cur_url[i] + "/";
    //}
    //new_url += id;
    //
    //$("a[name='fb_share']").attr('share_url', new_url);

    $.post("/photo/photo_details/" + type + "/" + id, { }, function(data) {

        $("dfn#date_uploaded").html(data.date_uploaded);
        $("dfn#caption").html(data.caption);
        $("dfn#views").html(data.views);
        $("dfn#num_comments").html(data.num_comments);
    }, "json");
}


function configure_event_for_slideshow() {

    $("#slideshow img").fadeIn();

    var album_id = $("#album_id").val();
    var next_photoid = $("#next_photoid").val();
    var prev_photoid = $("#prev_photoid").val();
    var keyword = $("#keyword").val();
    var url = top.location.href;
    var bd = $("#search_date").val();
    var by_date = $("#by_date").val();
    var by_event = $("#by_event").val();
    var by_club = $("#by_club").val();
    var by_phgr = $("#by_phgr").val();
    var item_type = $('#it').val();

    var after_photoid;
    if(bd) {
        by_date = bd;
    }
    else {
        by_date = "all";
    }

    var opts = {
            album_id: $("#album_id").val(),
            next_photoid: $("#next_photoid").val(),
            prev_photoid: $("#prev_photoid").val(),
            keyword: $("#keyword").val(),
            url: top.location.href,
            by_date: $("#by_date").val(),
            by_event: $("#by_event").val(),
            by_club: $("#by_club").val(),
            by_phgr: $("#by_phgr").val(),
            item_type: $('#it').val(),
            by_date: ($("#search_date").val()) ? $("#search_date").val() : "all" 
    };

    $('#slideshow img').live("click", function(e) {
            
        var click_x_coor = e.pageX;

        var img_width = $(this).width();

        if(click_x_coor > (img_width/2 + $(this).offset().left)) {
             after_photoid = next_photoid;
        }
        else {
             after_photoid = prev_photoid;
        }

        if(url.search(/.+photo\/tagged_photos.+/) != -1) {
            top.location.href = "/photo/tagged_photos/" + keyword + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/searched_photos.+/) != -1) {
            top.location.href = "/photo/searched_photos/" + keyword + "/" + by_date + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/adv_searched_photos.+/) != -1) {
            top.location.href = "/photo/adv_searched_photos/" + keyword + "/" + by_date + "/" + by_event + "/" + by_club + "/" + by_phgr + "/" + after_photoid;
        }
        else {
            top.location.href = "/photo/index/" + album_id + "/" + after_photoid;
            //$.post("/photo/next_photo/" + album_id + "/" + after_photoid, {}, function(data) {
            //    var data = eval('(' + data + ')');
            //    $("#current_img").attr("src", data.current_img_src);
            //    $("#current_index").html(data.current_index);
            //    $("#iid").val(after_photoid);
            //    $("#next_photoid").val(data.next_photoid);
            //    $("#current_img").css("left", "50%");
            //    $("#current_img").css("top", "50%");
            //    $("#current_img").css("margin-left", data.half_img_width);
            //    $("#current_img").css("margin-top", data.half_img_height);
            //    $("#current_img").attr("height", data.img_height);
            //    $("#current_img").attr("width", data.img_width);$("#prev_photoid").val(data.prev_photoid);

            //    load_tag_for_item();
            //    load_photo_rate(item_type, after_photoid);
            //    load_photo_detail(item_type, after_photoid);
            //    load_comment(item_type, after_photoid);
            //}); 
        }

        setScrollPos();

        return false;
    });

    $(document).keydown(function(e){
        
        if(url.search(/.+photo\/(index|tagged_photos|searched_photos|adv_searched_photos)\/.+/) != -1) {
            if (e.keyCode == 39 || e.keyCode == 37) {

               if(e.keyCode == 39) {
                   after_photoid = next_photoid;
               }
               if(e.keyCode == 37) {
                   after_photoid = prev_photoid;
               }

               if(url.search(/.+photo\/tagged_photos.+/) != -1) {
                    top.location.href = "/photo/tagged_photos/" + keyword + "/" + after_photoid;
               }
               else if(url.search(/.+photo\/searched_photos.+/) != -1) {
                    top.location.href = "/photo/searched_photos/" + keyword + "/" + by_date + "/" + after_photoid;
               }
               else if(url.search(/.+photo\/adv_searched_photos.+/) != -1) {
                    top.location.href = "/photo/adv_searched_photos/" + keyword + "/" + by_date + "/" + by_event + "/" + by_club + "/" + by_phgr + "/" + after_photoid;
               }
               else {
                    top.location.href = "/photo/index/" + album_id + "/" + after_photoid;
               }

               setScrollPos();

               return false;
            }
        }
    });


    $('.next_photo').click(function() {
            
        after_photoid = next_photoid;

        if(url.search(/.+photo\/tagged_photos.+/) != -1) {
           top.location.href = "/photo/tagged_photos/" + keyword + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/searched_photos.+/) != -1) {
           top.location.href = "/photo/searched_photos/" + keyword + "/" + by_date + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/adv_searched_photos.+/) != -1) {
            top.location.href = "/photo/adv_searched_photos/" + keyword + "/" + by_date + "/" + by_event + "/" + by_club + "/" + by_phgr + "/" + after_photoid;
        }
        else {
           top.location.href = "/photo/index/" + album_id + "/" + after_photoid;
        }

        setScrollPos();

        return false;
    });


    $('.prev_photo').click(function() {
            
        after_photoid = prev_photoid;
        
        if(url.search(/.+photo\/tagged_photos.+/) != -1) {
           top.location.href = "/photo/tagged_photos/" + keyword + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/searched_photos.+/) != -1) {
           top.location.href = "/photo/searched_photos/" + keyword + "/" + by_date + "/" + after_photoid;
        }
        else if(url.search(/.+photo\/adv_searched_photos.+/) != -1) {
            top.location.href = "/photo/adv_searched_photos/" + keyword + "/" + by_date + "/" + by_event + "/" + by_club + "/" + by_phgr + "/" + after_photoid;
        }
        else {
           top.location.href = "/photo/index/" + album_id + "/" + after_photoid;
        }

        setScrollPos();

        return false;
    });

    $(".photo_thumb").click(function() {

        var thumb_photoid = $(this).attr("id").split("_")[2]; 

        if(url.search(/.+photo\/tagged_photos.+/) != -1) {
           top.location.href = "/photo/tagged_photos/" + keyword + "/" + thumb_photoid;
        }
        else if(url.search(/.+photo\/searched_photos.+/) != -1) {
           top.location.href = "/photo/searched_photos/" + keyword + "/" + by_date + "/" + thumb_photoid;
        }
        else if(url.search(/.+photo\/adv_searched_photos.+/) != -1) {
            top.location.href = "/photo/adv_searched_photos/" + keyword + "/" + by_date + "/" + by_event + "/" + by_club + "/" + by_phgr + "/" + thumb_photoid;
        }
        else {
           top.location.href = "/photo/index/" + album_id + "/" + thumb_photoid;
        }

        setScrollPos();

        return false;
    });

}

function configure_event_for_user_info() {

    $("#user_info a").click(function() {
            
        $('#user_info').hide(); 
        $('#user_info_edit').slideDown("normal"); 
        return false;
    });

    $("#user_info_edit input[value='Cancel']").click(function() {

        $('#user_info').show(); 
        $('#user_info_edit').slideUp("normal"); 
        return false;
    });

    $("#user_info_edit input[value='Save']").click(function() {
        
         if($("#user_info_edit").valid()) {
            var fname = $("#user_info_edit input[name='first_name']").val();
            var lname = $("#user_info_edit input[name='last_name']").val();
            var user = $("#user_info_edit input[name='username']").val();
            var pass = $("#user_info_edit input[name='password']").val();
            var email = $("#user_info_edit input[name='email']").val();

            $.post('/usercp/edit_user_info', {first_name: fname, last_name: lname, username: user, password: pass, email: email}, function() {
                       
                $('#usercp_info_tab').load('/usercp/user_info', function() {
                    
                    configure_event_for_user_info();
                }).hide().slideDown(); 
            });
         }

         return false;
    });
}


function configure_event_for_user_events() {

    var usercp_tabs = $("#usercp_container").tabs();
    var selected;

    $("#usercp_events_tab a[name='create_new_event']").click(function() {

        selected = usercp_tabs.tabs('option', 'selected');

        $("#usercp_events").slideUp();
        $("#usercp_event_add").slideDown();

        return false;
    });

    $("#usercp_event_add input[value='Cancel']").click(function() {
            
        $("#usercp_event_add input,textarea,select").not("input[type='button']").val("");

        $("#usercp_event_add").slideUp();
        $("#usercp_events").slideDown();
        return false;
    });

    $("#usercp_event_add input[value='Save']").click(function() {

        if($("#usercp_event_add").valid()) {

            var name = $("#usercp_event_add input[name='event_name']").val();
            var event_date = $("#usercp_event_add input[name='event_date']").val();


            if($("#chkOther").is(':checked')) {

                var loc = $("#usercp_event_add input[name='event_location']").val();
                var street = $("#usercp_event_add input[name='event_street']").val();
                var city = $("#usercp_event_add input[name='event_city']").val();
                var prov = $("#usercp_event_add select[name='event_province']").val();
                var country = $("#usercp_event_add select[name='event_country']").val();
                var postal = $("#usercp_event_add input[name='event_postal_code']").val();
                var phone = $("#usercp_event_add input[name='event_phone_number']").val();

                $(this).parent().ajaxSubmit({
                    success: function(data) { 
                        $.post("/event/add_loc_event", {event_name: name, event_date: event_date, event_location: loc, event_street: street, event_city: city, event_province: prov, event_country: country, event_postal_code: postal, event_phone_number: phone, photo_id: data}, function() {
                    
                            $("#usercp_events_tab").slideUp().load("/usercp/user_events", function() {
                        
                                configure_event_for_user_events();
                                configure_event_for_datetime();
                            }).hide().slideDown();

                            $("#usercp_albums_tab").load("/usercp/user_albums", function() {
                                configure_event_for_user_albums();
                                configure_event_for_datetime();
                            });
                        });
                    }
                });
            }
            else {

                var loc_id = $("#usercp_event_add select[name='sel_event_location']").val();
                var loc_name = $("#usercp_event_add select[name='sel_event_location'] option:selected").text(); 
            
                $(this).parent().ajaxSubmit({
                    success: function(data) { 
                        $.post("/event/add_event", {event_name: name, event_date: event_date, event_location: loc_name, loc_id: loc_id, photo_id: data}, function() {
                    
                            $("#usercp_events_tab").slideUp().load("/usercp/user_events", function() {
                        
                                configure_event_for_user_events();
                                configure_event_for_datetime();
                            }).hide().slideDown();

                            $("#usercp_albums_tab").load("/usercp/user_albums", function() {
                                configure_event_for_user_albums();
                                configure_event_for_datetime();
                            });
                        });
                    }
                });
            }
        }

        return false;
    });

    $(".user_event_thumb a.delete_event").click(function() {
            
        var id = $(this).attr("name").split("_")[2];

        var answer = confirm("Are you sure you want to delete this event?");
        if(answer) {

           $.post("/event/delete_event", {event_id: id}, function() {
               
               $("#usercp_events_tab").load("/usercp/user_events", function() {
                    
                    configure_event_for_user_events();
                    configure_event_for_datetime();
                });

               $("#usercp_albums_tab").load("/usercp/user_albums", function() {
                    configure_event_for_user_albums();
                    configure_event_for_datetime();
                });
           }); 
        }

        return false;
    });

    $(".user_event_thumb a.edit_event").click(function() {
            
        var id = $(this).attr("name").split("_")[2];

        $("#usercp_events_tab").slideUp().load("/usercp/user_events_edit/" + id, function() { 

            configure_event_for_user_events();
            configure_event_for_datetime(); 
        }).hide().slideDown();

        return false;
    });

    $("#usercp_event_edit input[value='Cancel']").click(function() {

        $("#usercp_events_tab").slideUp().load("/usercp/user_events", function() {
            configure_event_for_user_events();
            configure_event_for_datetime();
        }).hide().slideDown();

        return false;
    });

    $("#usercp_event_edit input[value='Save']").click(function() {
        
        if($("#usercp_event_edit").valid()) {

            var name = $("#usercp_event_edit input[name='event_name']").val();
            var loc = $("#usercp_event_edit input[name='event_location']").val();
            var event_date = $("#usercp_event_edit input[name='event_date']").val();
            var street = $("#usercp_event_edit input[name='event_street']").val();
            var city = $("#usercp_event_edit input[name='event_city']").val();
            var prov = $("#usercp_event_edit select[name='event_province']").val();
            var country = $("#usercp_event_edit select[name='event_country']").val();
            var postal = $("#usercp_event_edit input[name='event_edit_postal_code']").val();
            var phone = $("#usercp_event_edit input[name='event_edit_phone_number']").val();

            var eid = $(this).attr("name").split("_")[2];
            var lid = $(this).attr("name").split("_")[3];

            $(this).parent().ajaxSubmit({
                success: function(data) {

                    $.post("/event/edit_event",  {event_id: eid, location_id: lid, event_name: name, event_location: loc, event_date: event_date, event_street: street, event_city: city, event_province: prov, event_country: country, event_postal_code: postal, event_phone_number: phone}, function() {
                    
                    $("#usercp_events_tab").slideUp().load("/usercp/user_events", function() {
                            configure_event_for_user_events();
                            configure_event_for_datetime();
                        }).hide().slideDown();
                    });

                    $("#usercp_albums_tab").load("/usercp/user_albums", function() {
                        configure_event_for_user_albums();
                        configure_event_for_datetime();
                    });
                }
            });
        }
    });
}


function configure_event_for_user_albums() {

    $("#usercp_albums a[name=create_new_album]").click(function() {

        $("#usercp_albums").slideUp();
        $("#usercp_album_add").slideDown();

        return false;
    });

    $("#usercp_album_add input[value='Cancel']").click(function() {
            
        $("#usercp_album_add input,textarea,select").not("input[type='button']").val("");

        $("#usercp_album_add > *").val();
        $("#usercp_album_add").slideUp();
        $("#usercp_albums").slideDown();
        return false;
    });

    $("#usercp_album_add input[value='Save']").click(function() {

        if($("#usercp_album_add").valid()) {    

            //var loc = $("#usercp_album_add input[name='album_location']").val();
            var loc = $("#usercp_album_add select[name='album_location']").val();
            var data_started = $("#usercp_album_add input[name='album_date_started']").val();
            var eid = $("#usercp_album_add select[name='for_event']").val();

            $.post("/album/create_album", {album_location: loc, album_date_started: data_started, event_id: eid}, function(new_album_id) {

                //$("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {
                $("#usercp_albums_tab").slideUp().load("/usercp/user_albums_edit/" + new_album_id, function() {
                    $("#usercp_albums_tab").append("<input id='new_album_id' type='hidden' value='" + new_album_id + "' />");
                    configure_event_for_user_albums();
                }).hide().slideDown();
            });
        }

        return false;
    });

    $(".user_album_thumb a.delete_album").click(function() {
            
        var id = $(this).attr("name").split("_")[2];

        var answer = confirm("Are you sure you want to delete this album?");
        if(answer) {

            $.post("/album/delete_album", {album_id: id}, function() {

                $("#usercp_albums_tab").load("/usercp/user_albums", function() {
                    
                    configure_event_for_user_albums();
                })
            });
        }

        return false;
    });

    $(".user_album_thumb a.edit_album").click(function() {
        
        var id = $(this).attr("name").split("_")[2];

        $("#usercp_albums_tab").slideUp().load("/usercp/user_albums_edit/" + id, function() {
            
            $("#usercp_albums_tab").append("<input id='new_album_id' type='hidden' value='" + id + "' />");
            configure_event_for_user_albums();
        }).hide().slideDown();

        return false;
    });

    $(".user_album_thumb a.view_album").click(function() {
        
        alert("TODO");
        return false;
    });

    $("#usercp_album_edit input[value='Cancel']").click(function() { 

        $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

            configure_event_for_user_albums();
        }).hide().slideDown();

        return false;
    });

    $("#usercp_album_edit input[value='Save']").click(function() {

        var id = $(this).attr("name").split("_")[2];

        if($("#usercp_album_edit").valid()) {    

            //var loc = $("#usercp_album_edit input[name='album_location']").val();
            var loc = $("#usercp_album_edit select[name='album_location']").val();
            var date_started = $("#usercp_album_edit input[name='album_date_started']").val();
            var eid = $("#usercp_album_edit select[name='for_event']").val();

            $.post("/album/edit_album", {album_id: id, album_location: loc, album_date_started: date_started, event_id: eid}, function() {
                  $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {
                       configure_event_for_user_albums();
                  }).hide().slideDown();
            });
        }

        return false;
    });

    $("#album_edit_nav a#info").click(function() {
            
        $("#edit_photos").slideUp();
        $("#add_more_photos").slideUp();
        $("#usercp_album_edit").slideDown();
        return false;
    });

    $("#album_edit_nav a#more").click(function() {
            
        $("#usercp_album_edit").slideUp();
        $("#edit_photos").slideUp();
        $("#add_more_photos").slideDown();
        return false;
    });

    $("#album_edit_nav a#edit").click(function() {
        
        var id = $("#usercp_albums_tab #new_album_id").val();

        $("#edit_photos").load("/usercp/usercp_album_photos_reload/" + id, function() {

            $("#edit_photos input[value='Cancel']").click(function() { 

                $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

                    configure_event_for_user_albums();
                }).hide().slideDown();

                return false;
            });

            $("#edit_photos input[value='Save']").click(function() {

                $("#edit_photos div.edited_photo").each(function() {

                    var photo_id = $(this).attr("id").split("_")[1];

                    if($($(this).children()[8]).attr("checked")) {
                        
                        $.post("/photo/delete_photo", {photo_id: photo_id}); 
                    }
                    else {

                      if($($(this).children()[6]).attr("checked")) {

                          var album_id = $($(this).children()[6]).attr("id").split("_")[1];
                          var cover_id = $($(this).children()[6]).attr("id").split("_")[2];
                          $.post("/album/edit_album_cover", {album_id: album_id, cover_id: cover_id}); 
                      }

                      var caption = $($(this).children()[0]).find("textarea").val();
                      $.post("/photo/edit_photo/" + photo_id, {caption: caption});            
                    }
                });

                $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

                    configure_event_for_user_albums();
                }).hide().slideDown();

                return false;
            });
        });
            
        $("#usercp_album_edit").slideUp();
        $("#add_more_photos").slideUp();
        $("#edit_photos").slideDown();

        return false;
    });

     $("#edit_photos input[value='Cancel']").click(function() { 

        $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

            configure_event_for_user_albums();
        }).hide().slideDown();

        return false;
    });

    $("#edit_photos input[value='Save']").click(function() {

        $("#edit_photos div.edited_photo").each(function() {

            var photo_id = $(this).attr("id").split("_")[1];

            if($($(this).children()[8]).attr("checked")) {
                
                $.post("/photo/delete_photo", {photo_id: photo_id}); 
            }
            else {

                if($($(this).children()[6]).attr("checked")) {

                    var album_id = $($(this).children()[6]).attr("id").split("_")[1];
                    var cover_id = $($(this).children()[6]).attr("id").split("_")[2];

                    $.post("/album/edit_album_cover", {album_id: album_id, cover_id: cover_id}); 
                }

                var caption = $($(this).children()[0]).find("textarea").val();
                $.post("/photo/edit_photo/" + photo_id, {caption: caption});            
            }
        });

        $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

            configure_event_for_user_albums();
        }).hide().slideDown();

        return false;
    });

    $("input[name='album_edit_photos']").click(function(){
        $(this).attr('checked', true);
    });

    $("#add_more_photos input[value='Finish']").click(function() {
            
        $("#usercp_albums_tab").slideUp().load("/usercp/user_albums", function() {

            configure_event_for_user_albums();
        }).hide().slideDown();

        return false;
    });
}


function configure_event_for_datetime() {

    $("#event_date").datetime({ userLang	: 'en', americanMode: true, });
    //$("#album_date_started").datetime({ userLang	: 'en', americanMode: true, });
}

function configure_form_validation() {

    $.validator.addMethod('postalCode', function (value) { 
        if(value) {
            return /^[A-Za-z]\d[A-Za-z][- ]?\d[A-Za-z]\d\s*$/.test(value); 
        }
        else {
            return true;
        }
    }, 'Please enter a valid Canadian postal code.');

    $.validator.addMethod('phoneNumber', function (value) { 
        if(value) {
            return /^(\d(\.|-| )?\d\d\d(\.|-| )?)?\d\d\d(\.|-| )?\d\d\d(\.|-| )?\d\d\d\d\s*$/.test(value); 
        }
        else {
            return true;
        }
    }, 'Please enter a valid phone number.');
    
    $("#user_info_edit").validate({
        rules: {
            password: {
				required: true,
				minlength: 6
			},
			retype_password: {
				required: true,
				minlength: 6,
				equalTo: "#password"
			}
        }
    });

    $('#usercp_event_add').validate({
        rules: {
            event_poster: {
                required: true,
                accept: "jpg|jpeg|gif|png"
            },
            sel_event_location: {
                required: "#chkOther:unchecked"
            },
            event_location: {
                required: "#chkOther:checked"
            },
            event_street: {
                required: "#chkOther:checked"
            },
            event_city: {
                required: "#chkOther:checked"
            },
            event_province: {
                required: "#chkOther:checked"
            },
            event_country: {
                required: "#chkOther:checked"
            },
            event_postal_code: {
                postalCode: "#chkOther:checked" 
            },
            event_phone_number: {
                phoneNumber: "#chkOther:checked" 
            }
        }
    });

    $("#usercp_album_add").validate();
    $("#usercp_album_edit").validate();
    $("#phgr_login_box").validate();

    $("#phgr_signup_box").validate({
        rules: {
            password: {
				required: true,
				minlength: 6
			},
			retype_password: {
				required: true,
				minlength: 6,
				equalTo: "#password"
			},
            user_type: "required"
        }
    });
}


function configure_event_photographer() {

    $("#phgr_login_box input[name='login_username']").focus();

    $("#creat_account a").click(function() {

        $("#phgr_signup_box input[type='text']").val("");
        //$("#phgr_signup_box").animate({opacity: 1.0}, 1000);        
        $("#phgr_signup_box").slideDown();

        return false;
    });

    $("#phgr_login_box input[value='Sign In']").click(function() {

        if($("#phgr_login_box").valid()) {
            
           var l_user = $("#phgr_login_box input[name='login_username']").val(); 
           var l_pass = $("#phgr_login_box input[name='login_password']").val(); 

           $.post("/login/login_validate", {provided_username: l_user, provided_password: l_pass}, function(data) {
               if(data == "NO") {
                    $("#phgr_login_error").html("<i style='color:red'>The username or password you entered is not correct.</i>");
               }
               else if(data == "YES") {
                    $("#phgr_login_error").html("");
                    top.location.href = "/usercp"; 
               }
               else {
                    $("#statusmsg").html(data); 
                    $("#statusmsg").slideDown();
               }
            });
        }

        return false;
    });

    $("#phgr_signup_box input[value='Create Account']").click(function() {

        if($("#phgr_signup_box").valid() && $("#phgr_username_error").is(':empty') && $("#phgr_email_error").is(':empty')) {
            
            var recaptcha_challenge_field = $("input[name='recaptcha_challenge_field']").val();
            var recaptcha_response_field = $("input[name='recaptcha_response_field']").val();

            $.post("/login/validate_recaptcha", {recaptcha_challenge_field: recaptcha_challenge_field, recaptcha_response_field: recaptcha_response_field}, function(data) {

                if(data == "YES") {
                    var type = $("#phgr_signup_box input[type='radio']:checked").val();
                    var fn = $("#phgr_signup_box input[name='first_name']").val();
                    var ln = $("#phgr_signup_box input[name='last_name']").val();
                    var email = $("#phgr_signup_box input[name='email_address']").val();
                    var user = $("#phgr_signup_box input[name='username']").val();
                    var pass = $("#phgr_signup_box input[name='password']").val();
                    var pass = $("#phgr_signup_box input[name='retype_password']").val();

                    $.post("/login/phgr_sign_up", {first_name: fn, last_name: ln, email: email, username: user, password: pass, type: type}, function() {
                        //$("#phgr_signup_box").animate({opacity: 0.0}, 1000);
                        $("#phgr_signup_box").slideUp();
                        $("#statusmsg").slideDown();
                    });
                }
                else {
                    alert("The words you entered did not match. Please try again.");
                    return;
                }
            });
        }

        return false;
    });

    $("#phgr_signup_box input[name='username']").blur(function() {

        $.post("/login/is_username_available", {preferred_id: $(this).val()}, function(data) {
            if(data == "NO") {
                $("#phgr_username_error").html("<i style='color:red'>This username is not available.</i>");
            }
            else {
                $("#phgr_username_error").html("");
            }
        });

        return false;
    });

    $("#phgr_signup_box input[name='email_address']").blur(function() {

        $.post("/login/is_email_available", {preferred_email: $(this).val()}, function(data) {
            if(data == "NO") {
                $("#phgr_email_error").html("<i style='color:red'>This email is already associcated with another account.</i>");
            }
            else {
                $("#phgr_email_error").html("");
            }
        });

        return false;
    });
}


function configure_event_for_admin() {

    $("#admin_login_box input[name='login_username']").focus();

    $("#admin_login_box input[value='Sign In']").click(function() {
            
        if($("#admin_login_box").valid()) {

           var l_user = $("#admin_login_box input[name='login_username']").val(); 
           var l_pass = $("#admin_login_box input[name='login_password']").val(); 

           $.post("/login/login_validate", {provided_username: l_user, provided_password: l_pass}, function(data) {
               if(data == "NO") {
                    $("#admin_login_error").html("<i style='color:red'>The username or password you entered is not correct.</i>");
               }
               else {
                    $("#admin_login_error").html("");
                    top.location.href = "/admincp"; 
               }
            });
        }

        return false;
    });
}

function admincp_show_edit_form() {
        $('#user_info').hide(); 
        $('#user_info_edit').slideDown("normal");
}

function admincp_cancel_edit_info() {
    $('#user_info').show(); 
    $('#user_info_edit').slideUp("normal");
}

function admincp_save_edit_info() {

    var selected =  $("#admincp").tabs('option', 'selected');
    if($("#user_info_edit").valid()){

        var fname = $("#user_info_edit input[name='first_name']").val();
        var lname = $("#user_info_edit input[name='last_name']").val();
        var user = $("#user_info_edit input[name='username']").val();
        var pass = $("#user_info_edit input[name='password']").val();
        var email = $("#user_info_edit input[name='email']").val();

        $.post('/admincp/edit_user_info', {first_name: fname, last_name: lname, username: user, password: pass, email: email}, function() {
                  
            $("#admincp").tabs('load', selected);
           //top.location.href = "/admincp";
        });
    }
}
    

function admincp_del_event(id) {

    var event_id = id.split("_")[2];

    var answer = confirm("Are you sure you want to delete this event?");

    if(answer) {
        $.post("/event/delete_event", {event_id: event_id}, function() {
            
            var row = $("#" + id);
            row.parent().parent().remove();
        }); 
    }
}

function admincp_edit_event(id) {

    var item_id = id.split("_")[2];
    $("#admincp_events_container #visible_row_" + item_id).hide();
    $("#admincp_events_container #hidden_row_" + item_id).show();
}

function admincp_cancel_edit_event(id) {

    var item_id = id.split("_")[2];
    $("#admincp_events_container #hidden_row_" + item_id).hide();
    $("#admincp_events_container #visible_row_" + item_id).show();
}


function admincp_update_event(id) {

    var selected =  $("#admincp").tabs('option', 'selected');

    var event_id = id.split("_")[2];
    var lid = id.split("_")[3];

    var name = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='name']").val();
    var loc = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='location']").val();
    var event_date = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='event_date']").val();
    var street = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='street']").val();
    var city = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='city']").val();
    var prov = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='province']").val();
    var country = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='country']").val();
    var postal = $("#admincp_events_container #hidden_row_" + event_id + " td input[name='postal_code']").val();

    $.post("/event/edit_event",  {event_id: event_id, location_id: lid, event_name: name, event_location: loc, event_date: event_date, event_street: street, event_city: city, event_province: prov, event_country: country, event_postal_code: postal}, function() {

       $("#admincp").tabs('load', selected); 
    });
}


function admincp_del_album(id) {

    var album_id = id.split("_")[2];

    var answer = confirm("Are you sure you want to delete this album?");

    if(answer) {
        $.post("/album/delete_album", {album_id: album_id}, function() {
            
            var row = $("#" + id);
            row.parent().parent().remove();
        }); 
    }
}


function admincp_edit_album(id) {

    var item_id = id.split("_")[2];
    $("#admincp_albums_container #visible_row_" + item_id).hide();
    $("#admincp_albums_container #hidden_row_" + item_id).show();
}

function admincp_cancel_edit_album(id) {

    var item_id = id.split("_")[2];
    $("#admincp_albums_container #hidden_row_" + item_id).hide();
    $("#admincp_albums_container #visible_row_" + item_id).show();
}

function admincp_update_album(id) {

    var selected =  $("#admincp").tabs('option', 'selected');

    var aid = id.split("_")[2];
    var eid = id.split("_")[3];

    var loc = $("#admincp_albums_container #hidden_row_" + aid + " td input[name='location']").val();
    var date_started = $("#admincp_albums_container #hidden_row_" + aid + " td input[name='date_started']").val();

    $.post("/album/edit_album", {album_id: aid, album_location: loc, album_date_started: date_started, event_id: eid}, function() {
        
        $("#admincp").tabs('load', selected);
    });  
}

function admincp_del_photo(id) {

    var photo_id = id.split("_")[2];

    var answer = confirm("Are you sure you want to delete this photo?");

    if(answer) {
        $.post("/photo/delete_photo", {photo_id: photo_id}, function() {
            
            var row = $("#" + id);
            row.parent().parent().remove();
        }); 
    }
}

function admincp_edit_photo(id) {

    var item_id = id.split("_")[2];
    $("#admincp_photos_container #visible_row_" + item_id).hide();
    $("#admincp_photos_container #hidden_row_" + item_id).show();
}

function admincp_cancel_edit_photo(id) {

    var item_id = id.split("_")[2];
    $("#admincp_photos_container #hidden_row_" + item_id).hide();
    $("#admincp_photos_container #visible_row_" + item_id).show();
}

function admincp_update_photo(id) {

    var selected =  $("#admincp").tabs('option', 'selected');

    var photo_id = id.split("_")[2];

    var caption = $("#admincp_photos_container #hidden_row_" + photo_id + " textarea").val();

    $.post("/photo/edit_photo/" + photo_id, {caption: caption}, function() {
        
        $("#admincp").tabs('load', selected);
    });
}

function admincp_del_comment(id) {

    var comment_id = id.split("_")[2];

    var answer = confirm("Are you sure you want to delete this comment?");

    if(answer) {
        $.post("/admincp/delete_comment", {comment_id: comment_id}, function() {
            
            var row = $("#" + id);
            row.parent().parent().remove();
        }); 
    }
}

function admincp_edit_comment(id) {

    var item_id = id.split("_")[2];
    $("#admincp_comments_container #visible_row_" + item_id).hide();
    $("#admincp_comments_container #hidden_row_" + item_id).show();
}

function admincp_cancel_edit_comment(id) {

    var item_id = id.split("_")[2];
    $("#admincp_comments_container #hidden_row_" + item_id).hide();
    $("#admincp_comments_container #visible_row_" + item_id).show();
}

function admincp_update_comment(id) {

    var selected =  $("#admincp").tabs('option', 'selected');

    var comment_id = id.split("_")[2];
    var body = $("#admincp_comments_container #hidden_row_" + comment_id + " textarea").val()

    $.post("/comment/edit_comment", {comment_id: comment_id, body: body}, function() {

        $("#admincp").tabs('load', selected);
    });
}

function admincp_del_user(id) {

    var user_id = id.split("_")[2];

    var answer = confirm("Are you sure you want to delete this user?");

    if(answer) {
        $.post("/admincp/delete_user", {user_id: user_id}, function() {
            
            var row = $("#" + id);
            row.parent().parent().remove();
        }); 
    }
}

function configure_event_for_tagging() {

    var ratable = $('#ratable').val();

    if(ratable == 'NO') {

        //$("#add_tag_link").mouseenter(function() {
        //    $("#add_tag_link span#signin_span").remove();
        //    $("#add_tag_link").append($("<span id='signin_span' style='margin-left:10px;'>Sign in to tag.</span>")); 
        //});

        //$("#add_tag_link > *").mouseleave(function() {
        //    $("#add_tag_link span#signin_span").remove();
        //});
    }
    else {

        $("#add_tag_link").click(function() {
                

            if($("#add_tag_container").css("display") == "none") {

                //$("#add_tag_container").slideDown();
                $("#add_tag_container").animate({
                    width: "250px",
                    height: "25px"
                    }, 500);

                $("#add_tag_container input[type='text']").val("").focus();
            }
            else {
                //$("#add_tag_container").slideUp();
                $("#add_tag_container").animate({
                    width: "0px",
                    height: "0px"
                }, 500, function() {
                    $("#add_tag_container").css({"display":"none"}); 
                });
            }

            return false;
        });

        $("#add_tag_container input[type='button']").click(function() {

            var item_type = $("#it").val();
            var item_id = $("#iid").val();
            var tag = $("#add_tag_container input[type='text']").val();

            if(tag) {
                $.post("/tag/save_tag", {item_type: item_type, item_id: item_id, tag: tag}, function() {
                    //$("#add_tag_container").slideUp();  
                    $("#add_tag_container").animate({
                            width: "0px",
                            height: "0px"
                        }, 1000, function() {
                            $("#add_tag_container").css({"display":"none"}); 
                    });

                    load_tag_for_item();
                });
            }

            return false;
        });
    }
}

function load_tag_for_item() {

    var item_type = $("#it").val();
    var item_id = $("#iid").val();

    $.post("/tag/get_tag_for_id", {item_type: item_type, item_id: item_id}, function(data) {
        $("#item_tag").html(data);         
    });
}

function retrieve_info() {

    var info = $("#info_retrieval input[type='text']").val();

    if(info) {

        $.post("/login/does_user_exist", {info: info}, function(data) {
            
            if(data == "YES") {    
                $("div#msg").html("<span style='color:white; font-style:normal;'>An email with instruction to reset your password has been sent to you.</span>");
            }
            else {
                $("div#msg").html("<span>The specified username or email does not exist.</span>");
            }
        });
    }
    else {

        $("div#msg").html("<span>Please specify username or email.</span>");
    }
}


function reset_password() {

    if($("#password_reset").valid()) {
        var pass = $("#password_reset input[name='password']").val();;
        var token = $("#password_reset input[type='hidden']").val();;

        $.post("/login/do_reset_password", {token: token, password: pass}, function(data) {

            top.location.href = "/login/phgr_sign_in";        
        });
    }
}



function configure_event_for_searching() {

    $("#search_by_date").change(function() {

        var bd = $(this).val();
        var keyword = $("#keyword").val();
        if(bd) {
            by_date = bd;
        }
        else {
            by_date = "all";
        }

        top.location.href = "/photo/search/" + keyword + "/" + by_date;

        return false;
    });

    $("#pagination_for_search a").click(function() {
        
        var page_num = $(this).attr("name");
        var keyword = $("#keyword").val();
        var bd = $("#search_by_date").val();

        if(bd) {
            by_date = bd;
        }
        else {
            by_date = "all";
        }

        top.location.href = "/photo/search/" + keyword + "/" + by_date + "/" + page_num;

        return false; 
    });

    $("#show_more_comments").click(function() {

        var comment_limit = $("#comment_limit").val();
        var num_comments = $("#item_num_comments").val();
        var iid = $('#iid').val();
        var it = $('#it').val();

        comment_limit = parseInt(comment_limit) + 5;

        if(comment_limit < num_comments) {
            $("#comment_limit").val(comment_limit);

            $('#comment_listing').load('/comment/get_comment/' + it + '/' + iid + '/' + comment_limit, function() {
                configure_event_for_comment_replying();
            });
        }
        else {
            comment_limit = num_comments;
            $("#comment_limit").val(num_comments);

            $('#comment_listing').load('/comment/get_comment/' + it + '/' + iid + '/' + comment_limit, function() {
                configure_event_for_comment_replying();
            });

            $("#show_more_comments").hide();
        }

        return false;
    });
}

function setScrollPos() {

    var scrollPosName = "SCROLL_POS";
    var scrollPosVal = $(document).scrollTop();
    var days = 1;

    setCookie(scrollPosName, scrollPosVal, days);
}

function getScrollPos() {

    var url = top.location.href;

    if(url.search(/.+photo\/(index|tagged_photos|searched_photos|adv_searched_photos)\/.+/) != -1) {

        var scrollPosName = "SCROLL_POS";
        var scrollPosVal = getCookie(scrollPosName);
        $(document).scrollTop(scrollPosVal); 
    }
}

function setCookie(name, value, days) {

	if(days) {

		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else {
        var expires = "";
    }

	document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {

	var nameEQ = name + "=";
	var cookies = document.cookie.split(';');

	for(var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i];
		while (cookie.charAt(0) == ' ') {
            cookie = cookie.substring(1, cookie.length);
        }

		if (cookie.indexOf(nameEQ) == 0) {
            return cookie.substring(nameEQ.length,cookie.length);
        }
	}

	return null;
}

