
$(document).ready(function() {
    
    //Login functionality
    var loginShowed = false;

    if($('.pg-home section, .pg-login section').hasClass('is-login')){
        var $regForm = $('form[name="registration-form"]'),
        $loginForm = $('form[name="login-form"]');
        loginShowed = true;
        $('.toggle-btn').text('Sign Up');
        $regForm.hide();
        $loginForm.show();
    }
    
    $('.toggle-btn').bind('click', function(e){
        e.preventDefault();
        
        var $regForm = $('form[name="registration-form"]'),
        $loginForm = $('form[name="login-form"]'),
        $this = $(e.currentTarget);

        if(loginShowed){
            $loginForm.hide(200, function(){
                $regForm.show(200);
            })
            $this.text('Login');
        }else{
            $regForm.hide(200, function(){
                $loginForm.show(200);
            });
            $this.text('Sign Up');
        }
        loginShowed = !loginShowed;
        
    });
    
    //Go register
    $(".clearfix").delegate("#go-register", "click", function(e){
        
        var icode = '', url = '', s1 = '', s2 = '';
        e.preventDefault();
        
        if($("#sf_guard_user_invitation_code").val() != "")
            icode = 'invitation_code='+$("#sf_guard_user_invitation_code").val();
        
        if($("#sf_guard_user_account_url").val() != "")
            url = 'url='+$("#sf_guard_user_account_url").val();
        
        if(icode != '' || url != '')
            s1 = '?';
        
        if(icode != '' && url != '')
            s2 = '&';
        
        window.location = "/register"+s1+icode+s2+url;
    });

    //Dinamically update the EventGroup options based on EventOption
    $("#ticket_event_option").change(function(){

        var eoSelect = $("#ticket_event_option");
        var egDiv = $("#event-group-div");

        $.get('/ticket/dynamicFields?eoId='+eoSelect.val(),
            function(data){
                egDiv.html(data);
            }
            );
    });

    //Change is_active status for Events
    $(".clearfix").delegate("#upcoming-events .status img, #imported-events .status img", "click", function(){

        var stringId = $(this).attr('id');
        var id = stringId.substr(7);
        var updatedElement1 = $('#status_'+id).parent("td");
        var updatedElement2 = $('#itatus_'+id).parent("td");
        $('#status_'+id).closest('tr').toggleClass('not-listed');
        $('#itatus_'+id).closest('tr').toggleClass('not-listed');

        updatedElement1.empty().html("<img src=\"/images/icons/ajax-loader-30.gif\">");
        updatedElement2.empty().html("<img src=\"/images/icons/ajax-loader-30.gif\">");
        $.post('/event/ajaxChangeEventActiveStatus?event_id='+id,
            function(data){
                updatedElement1.html(data);
                var data2 = data.replace("status", "itatus");
                updatedElement2.html(data2);
            }
        );
    });

    // Edit ticket description on Events Page

    $(".ticket_description").editable('/event/ajaxSaveTicketDescription', {
        indicator : "<img src='/images/icons/ajax-loader.gif'>",
        type : 'textarea',
        submitdata: {
            _method: "put",
            "ticket[_csrf_token]": $("#csrf_token").text()
        },
        select : true,
        submit : 'Save',
        cancel : 'Cancel',
        onblur : "ignore",
        placeholder:'Tell us about your seats',
        cssclass : "editable",
        id   : 'ticket[id]',
        name : 'ticket[description]',
        style: "height: 100px;",
        rows: "3"
    });

    var setPriceQty = function(){
        //Change price value for Events
        $("#upcoming-events .price-edit").editable('/event/ajaxSaveEventPrice', {
            indicator : "<img src='/images/icons/ajax-loader.gif'>",
            submitdata: {
                _method: "put"
            },
            onblur: 'submit',
            placeholder:'Add Price',
            callback : function(value, settings) {
                var $_this = $(this);
                var $imgStatus = $_this.closest('tr').find('td.status img');
                var $quantity = $_this.closest('tr').find('.quantity-edit');

                // if quantity and price is not empty call to change estatus
                if(value != "")
                {                    
                    if ($imgStatus.attr('title')=="Display") $imgStatus.click();
                }

                if (value == "" && $quantity.html()=="Add Quantity")
                {
                    if ($imgStatus.attr('title')=="Don't Display") $imgStatus.click();
                }
            }
        });

        //Change quantity value for Events
        $("#upcoming-events .quantity-edit").editable('/event/ajaxSaveEventQuantity', {
            indicator : "<img src='/images/icons/ajax-loader.gif'>",
            submitdata: {
                _method: "put"
            },
            onblur: 'submit',
            placeholder:'Add Quantity',
            callback : function(value, settings) {
                var $_this = $(this);
                var $price = $_this.closest('tr').find('.price-edit');
                var $imgStatus = $_this.closest('tr').find('td.status img');

                // if quantity and price is not empty call to change estatus
                if(value != "")
                {                    
                    if ($imgStatus.attr('title')=="Display") $imgStatus.click();
                }

                if (value == "" && $price.html()=="Add Price")
                {
                    if ($imgStatus.attr('title')=="Don't Display") $imgStatus.click();
                }
            }
        });
    }
    setPriceQty();

    var ticket_id = $(".ticket_id").text();
    var url_user = $("#url_user").text();
    var session_id = $(".session_id").text();

    $("#upload_photos").uploadify({
        'uploader': '/swf/uploadify.swf',
        'cancelImg': '/images/uploadify/cancel.png',
        'script': '/event/saveImage?ticket_id=' + ticket_id,
        'folder': '/uploads/photos/' + url_user,
        'scriptData': {'unseatme': + session_id},
        'multi': true,
        'buttonText': 'Select Files',
        'displayData': 'speed',
        'simUploadLimit': 2,
        'onAllComplete' : function(event,data) {

            $.ajax({
                type: 'GET',
                url:'/event/ajaxThumbnailList?ticket_id=' + $(".ticket_id").text(),
                success: function(imgdata){
                    $('#thumbnail_list').html(imgdata);
                    setCaptionEvent();
                }
            });
            
        },
        'onError': function (event, queueID ,fileObj, errorObj) {
            var msg;
            if (errorObj.status == 404) {
                alert('Could not find upload script. Use a path relative to: '+'<?= getcwd() ?>');
                msg = 'Could not find upload script.';
            } else if (errorObj.type === "HTTP")
                msg = errorObj.type+": "+errorObj.info;
            else if (errorObj.type ==="File Size")
                msg = fileObj.name+'<br>'+errorObj.type+' Limit: '+Math.round(errorObj.sizeLimit/1024)+'KB';
            else
                msg = errorObj.type+": "+errorObj.text;
            //alert(msg);
            $("#fileUpload" + queueID).fadeOut(250, function() {
                $("#fileUpload" + queueID).remove();
            });
            return false;
        }
    });

    $("#add_photo").delegate("a", "click", function(e){
        e.preventDefault();
        var uploadPhotosDiv = $("#upload_photos_div");
        var textLink = $(this).text();

        if(textLink == 'Add Photos')
        {
            uploadPhotosDiv.removeClass('hidden');
            $(this).text('Cancel Add Photos');
        }
        else if(textLink == 'Cancel Add Photos')
        {
            uploadPhotosDiv.addClass('hidden');
            $(this).text('Add Photos');
        }

    });

    // Prevent not authenticated user
    var checkIsAuthenticated = function(e){
        if ($(e.currentTarget).attr('type') != 'submit')
            e.preventDefault();
        $.get('/event/checkIsAuthenticated', function(data){
            if(!data){
                window.location.reload();
            }
        });
    }    

    $("#upload_photos_div").delegate("#upload_photosUploader", "click", checkIsAuthenticated);
    $("#upcoming-events").delegate(".status", "click", checkIsAuthenticated);
    $("#upcoming-events").delegate(".price-edit input", "focusin", checkIsAuthenticated);
    $("#upcoming-events").delegate(".quantity-edit input", "focusin", checkIsAuthenticated);
    $("#thumbnail_list").delegate('.cboxElement', "click", checkIsAuthenticated);
    $("#aside").delegate('button[type="submit"]', "click", checkIsAuthenticated);



    //Checker: Checks if a job is running
    if($('#task-info').length)
    {
        var task = $('#task-value').val();
        var toUpdate = $('#upcoming-events');
        var toUpdate2 = $('#imported-events');
        var ticketId = $('#ticket_id').val();
        var accountId = $('#account_id').val();

        var getData = function() {
            $.get('/event/checkRunningTask?task='+task,
                function(data) {
                    if(!data)
                    {
                        clearInterval(timer);
                        $.get('/event/refreshUpcomingEvents?ticket_id='+ticketId+'&account_id='+accountId, function(data2){
                            toUpdate.html(data2);
                            setPriceQty();
                        });
                        $.get('/event/refreshImportedEvents?ticket_id='+ticketId+'&account_id='+accountId, function(data3){
                            toUpdate2.html(data3);
                            setPriceQty();
                        });
                        $('#task-info').remove();
                    }
                });
        }
        var timer = setInterval( getData, 10000);
    }
    
    // Seatmaps in Colorbox Modal
    $('a[rel="seatmap"]').colorbox({
        scrolling: false,
        arrowKey: false,        
        onComplete:function(){
            $('#cboxPrevious').remove();
            $('#cboxNext').remove();
            $('#cboxCurrent').remove();
            $.colorbox.resize();
        }
    });

    //Promote your tickets modal
    $('a[rel="prompt-promote"]').colorbox({
        open: true
    });
   
    //Sell tickets - imgs caption
    var ajaxForm = function($target){

        $($target).ajaxForm( {
            target: '#cboxLoadedContent',
            beforeSubmit:  function()
            {
                $('#cboxLoadedContent').find('form').append("<img class='ajax-status' src=\"/images/icons/ajax-loader.gif\">");
            },
            success: function()
            {
                $('.ajax-status').remove();
                $.colorbox.resize();
                ajaxForm($target);
            }
        });
    }

    var setCaptionEvent = function(){
        $('a[rel="caption"]').colorbox({
            scrolling: false,
            current: "Caption {current} of {total}",
            onComplete:function()
            {
                $.colorbox.resize();
                ajaxForm('form.caption');
            }
        });
    }
    setCaptionEvent();

    $('body').delegate('.remove-caption', 'click', function(e){
        e.preventDefault();
        if(confirm ("Are you sure?")){
            $.ajax({
                url:'/event/ajaxDeleteMedia?id='+$('#media_id').val(),
                success: function(data){
                    if(data.status){
                        window.location.reload();
                    }else{
                        alert('Photo was not deleted');
                    }
                }
            });
        }
    });
    
    // set modal to contact form
    $('a[rel="contact"]').colorbox({
        scrolling: false,
        arrowKey: false,        
        onComplete:function(){
            $('#cboxPrevious').remove();
            $('#cboxNext').remove();
            $('#cboxCurrent').remove();
            
            $.colorbox.resize();
            ajaxForm('form.contact-form');
            

        }
    });
    /*
     * Promote Tickets
     */
    var prevEmailService = {
        $target : $('#gmail'),
        $link : $('#promote-menu a.selected')
    };
    
    $('#promote-menu a').bind('click', function(e){
        
        e.preventDefault();

        var $currentTarget = $(e.currentTarget),
        hash = e.currentTarget.hash;

        if( ! $currentTarget.hasClass('selected')){

            prevEmailService.$link.removeClass('selected');
            $currentTarget.addClass('selected');
            
            prevEmailService.$target.hide();
            $(hash).show();
        
            prevEmailService.$target = $(hash);
            prevEmailService.$link = $currentTarget;
        }
    });
    var inputVal = '';
    $('#promote-tickets input').bind('click', function(e){
        inputVal = $(e.currentTarget).val();
        $(this).focus();
        $(this).select();
    });
    
    $('#promote-tickets input').bind('focusout', function(e){
        $(e.currentTarget).val(inputVal);
    });

    $('#btn-updater').bind('click', function(e){
        e.preventDefault();
        if(confirm('Are you sure?')){
            window.location = $(e.currentTarget).attr('href');
        }
    });


    // ajax to resend verification email
    var setResendVerificationEmail = function(){
        $('a[rel="resend_verification"]').colorbox({
            scrolling: false,            
            onComplete: function()
            {
                $.colorbox.resize();
                $('#resend_verification_email').focus();                
                ajaxFormVerification('form.verification-email-form');
            }
        });
    }

    //Sell tickets - imgs caption
    var ajaxFormVerification = function($target){

        $($target).ajaxForm( {
            target: '#cboxLoadedContent',
            beforeSubmit:  function()
            {
                $('#cboxLoadedContent').find('form').append("<img class='ajax-status' src=\"/images/icons/ajax-loader.gif\">");
            },
            success: function(responseXML)
            {
                $('.ajax-status').remove();
                if (responseXML != "1")
                {
                    $.colorbox.resize();
                    $('#resend_verification_email').focus();   
                    ajaxFormVerification($target);
                }
                else
                {
                    $.colorbox.close();
                    window.location = '/login';
                }
            }
        });
    }

    setResendVerificationEmail();
    
    //Alt Facebook connect
    $(".fb_init").bind('click', function(e){
        
        var $target = "#refr";
        
        $.ajax({
            url: '/home/altFacebookConnect?fromAlt=' + $('.toggle-btn').text() + '&invitation_code=' + $('#sf_guard_user_invitation_code').val() + '&url=' + $('#sf_guard_user_account_url').val(),
            success: function(data){
                $('.toggle-btn').bind('click', function(e){
                    window.location = $(e.currentTarget).attr('href');
                });
                $($target).html(data);
            }
        });
        
    });
    
    $("#refr").delegate("#alt-facebook-connect-post", "click", function(e){
        
        var $form = "#alt-form";
        var $target = "#refr";
        
        $.ajax({
            type: 'post',
            url: '/home/processAltFacebookConnect?fromAlt=' + $('.toggle-btn').text(),
            data: $($form).serialize(),
            success: function(data){
                $($target).html(data);
            }
        });
        
    });
    
});

