//common methods for Topic or Content Item Page
var ContentTopic = {
    incrementContentItemPV: function(){
        ContentTopic.incrementPageView('ContentItem', cipage_content_item_id);
    },

    incrementTopicPV: function(){
        ContentTopic.incrementPageView('Topic', topicpage_topic_id );
    },

    incrementPageView: function(page_type,id){
        $.ajax({
            cache: false,
            type: "GET",
            url: '/topic/ajaxIncrementPageView',
            data: {page_type: page_type, id: id},
            success: function () {},
            error: function () {}
        });
    }
}

//for commenting on content item page
var CIComment = {
    post_data: null,

    freeing: false,

    initialise:function() {
        $('#btnAddComment').click(CIComment.addComment);
        $('.decoration').focus(CIComment.decorationBehavior);
        $('.realInput').blur(CIComment.realInputBehavior);
    },

    decorationBehavior: function () {
        var obj = $(this);
        obj.hide();
        obj.prev().show().focus();
    },

    realInputBehavior: function () {
        var obj = $(this);
        if($.trim(obj.val()).length == 0) {
            obj.hide();
            obj.next().show();
        }
    },

    addComment: function() {
        if(!CIComment.validate()) return false;

        CIComment.freeing = true;

        $.ajax({
            url: '/contentitem/ajaxAddComment',
            dataType: 'html',
            cache: false,
            data: CIComment.post_data,
            success: function(data) {
                $("#commentList").prepend(data);
                setTimeout("CIComment.freeing = false;",30000);
            },
            error: function()
            {
                alert('Adding comment failed');
                CIComment.freeing = false;
            }
        });

        return false;
    },

    validate: function() {
        if(CIComment.freeing) {
            alert('You have been commenting too fast, please slow down!');
            return false;
        }

        CIComment.post_data = {content_item_id:cipage_content_item_id};

        CIComment.post_data['content'] = $.trim($('#content').val());
        if(CIComment.post_data['content'].length < 5) {
            alert('The comment is too short')
            return false;
        }

        if(!is_user_logined) {

            CIComment.post_data['email'] = $.trim($('#email').val());
            if(!Creativo.Utility.checkEmail(CIComment.post_data['email'])) {
                alert('Email address invalid')
                return false;
            }

            CIComment.post_data['nickname'] = $.trim($('#nickname').val());
            if(CIComment.post_data['nickname'].length == 0) {
                alert('Name can not be empty')
                return false;
            }
        }

        return true;
    }
}

// used on You tube content item page and topic page for video selection
var YoutubeVideoBox = {
    initialise:function() {
        $('.btnYoubeThumb').click(YoutubeVideoBox.selectVideo);
    },

    selectVideo: function() {
        var youtube_id = $(this).attr('id').substring(14); //get string after btnYoubeThumb_
        var video_box = $('#youtubeVideoBox_'+youtube_id);
        if(video_box && video_box.is(':hidden')) {
            video_box.parent().find('.youTubePlayer').hide();
            video_box.show();
        }
        
        return false;
    }
}

// filmstrip for Gallery or Flcikr on homepage or topci page
var GalleryFilmstrip = {
    max_photos2show: 6,
    
    initialise:function(num) {
        if(num) {
            GalleryFilmstrip.max_photos2show = num;
        }
        $('.btnGalleryLeftMore').click(GalleryFilmstrip.moveLeft);
        $('.btnGalleryRightMore').click(GalleryFilmstrip.moveRight);
    },

    moveRight: function() {
        var rest_2_show = $(this).parent().parent().find('.galleryNav li:visible:last ~ li:lt('+GalleryFilmstrip.max_photos2show+')');
        GalleryFilmstrip.showPics(rest_2_show,$(this));
        return false;
    },

    moveLeft: function() {
        var rest_2_show = $(this).parent().parent().find('.galleryNav li:visible:first').prevAll(':lt('+GalleryFilmstrip.max_photos2show+')');
        GalleryFilmstrip.showPics(rest_2_show,$(this));
        return false;
    },

    showPics: function(pics2show,box) {
        if(pics2show.length > 0) {
            box.parent().parent().find('.galleryNav li').hide();
            pics2show.show();
        }
    }
}

//for Gallery or Flickr on Contentr Item Page
var FlickrGalleryBox = {

    initialise:function(num) {
        $('#btnCiGalleryLeftMore').click(FlickrGalleryBox.moveLeft);
        $('#btnCiGalleryRightMore').click(FlickrGalleryBox.moveRight);
        $('.btnCIGalleryThumb').click(FlickrGalleryBox.clickThumb);
    },

    moveRight: function() {
        var current = $('#ciGalleryMainPhoto span:visible:first');
        FlickrGalleryBox.showPhoto(current.next());
        return false;
    },

    moveLeft: function() {
        var current = $('#ciGalleryMainPhoto span:visible:first');
        FlickrGalleryBox.showPhoto(current.prev());
        return false;
    },

    clickThumb: function() {
        var pid = $(this).attr('id').substring(18);
        FlickrGalleryBox.showPhoto($('#ciGalleryMainPhoto_'+pid));
        return false;
    },

    showPhoto: function(photo2show) {
        if(photo2show.length > 0) {
            $('#ciGalleryMainPhoto span').hide();
            photo2show.css('display','block');
        }
    }
}

//for processing the answering on competition page
var CompetitionBox = {

    initialise: function() {
        $('#btnCompSubmit').click(CompetitionBox.submitAnswer);
        $('#btnSubNewsletter').click(CompetitionBox.subscribeNewsletter);
    },

    subscribeNewsletter: function() {
        $.ajax({
            url: '/user/ajaxSubscribeNewsletter',
            dataType: 'json',
            cache: false,
            success: function(data) {
                   $('#subNewsletter').remove();
                   $('#compAnswer').show();
            },
            error: function()
            {
                alert('subscription falied');
            }
        });

        return false;
    },

    submitAnswer: function() {
        var has_error = false;
        if ($('#friendName_1').length) {
            // means invite friends, create validations
            // check if all fields are not empty
            
            if ($('#friendName_1').val() == "" || $('#friendName_2').val() == "" || $('#friendName_3').val() == "" || $('#friendName_4').val() == "" || $('#friendName_5').val() == ""
                || $('#friendEmail_1').val() == "" || $('#friendEmail_2').val() == "" || $('#friendEmail_3').val() == "" || $('#friendEmail_4').val() == "" || $('#friendEmail_5').val() == "") {
                alert("Please complete all the names and emails");
                has_error = true;
            } else if (!validateEmail($('#friendEmail_1').val())) {
                alert("Your first email-address is invalid");
                has_error = true;
            } else if (!validateEmail($('#friendEmail_2').val())) {
                alert("Your second email-address is invalid");
                has_error = true;
            } else if (!validateEmail($('#friendEmail_3').val())) {
                alert("Your third email-address is invalid");
                has_error = true;
            } else if (!validateEmail($('#friendEmail_4').val())) {
                alert("Your fourth email-address is invalid");
                has_error = true;
            } else if (!validateEmail($('#friendEmail_5').val())) {
                alert("Your fifth email-address is invalid");
                has_error = true;
            }
            
        } 
        
        if (has_error == false) {
            var answer = $.trim($('#compInput').val());
            if(answer == '') return false;

            /* require invitation emails */
            if ($('#friendName_1').length) {
                $.ajax({
                    url: '/contentitem/ajaxAnswerCompetition',
                    dataType: 'json',
                    cache: false,
                    data: {
                            content_item_id:cipage_content_item_id, answer: answer, invite_email: 1, 
                            friendName_1: $('#friendName_1').val(), friendName_2: $('#friendName_2').val(), friendName_3: $('#friendName_3').val(), friendName_4: $('#friendName_4').val(), friendName_5: $('#friendName_5').val(),
                            friendEmail_1: $('#friendEmail_1').val(), friendEmail_2: $('#friendEmail_2').val(), friendEmail_3: $('#friendEmail_3').val(), friendEmail_4: $('#friendEmail_4').val(), friendEmail_5: $('#friendEmail_5').val(),
                            prize_name: $('#prize_name').val(), user_name: $('#user_name').val(), current_url: $(location).attr('href')
                            },
                    success: function(data) {
                            $('#compAnswer').remove();
                            $('#compAnswered').show();
                    },
                    error: function()
                    {
                        alert('Answering falied');
                    }
                });
            } else {
                $.ajax({
                    url: '/contentitem/ajaxAnswerCompetition',
                    dataType: 'json',
                    cache: false,
                    data: {content_item_id:cipage_content_item_id, answer: answer},
                    success: function(data) {
                            $('#compAnswer').remove();
                            $('#compAnswered').show();
                    },
                    error: function()
                    {
                        alert('Answering falied');
                    }
                });
            }
            
            return false;    
        }
    }

}


function validateEmail(id)  
{  
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
return emailPattern.test(id);  
 
}  
