﻿// JSLint Config:
/*jslint browser: true */
/*global cc, jQuery, tinyMCE, cc_resx_TR_Are_you_sure_delete_content, cc_resx_CDN_URL,
cc_resx_TR_Please_wait, cc_resx_TR_confirm_status_delete, cc_resx_TR_An_error_occurred_deleting,
cc_resx_TR_Deleting_Content_Please_wait, cc_resx_TR_Saving, cc_resx_TR_Total_Earned
cc_resx_TR_Topless_Pay, cc_resx_TR_mp_total_paid_to_date, cc_resx_TR_Chat_Pay
*/

//  myAffiliatesShowAll
//  Author: Kevin Burkitt
//  Date:   2010-03-22
//  
//  My Profile Pages Helper Functions
//
cc.myprofile = function() {

    return {
        postInProgress: false,

        init: function(container) {

            jQuery('.cc-delete', container).each(function() {
                var mediaId = jQuery(this).attr('cc:media');
                var starsValue = jQuery(this).attr('cc:stars');

                jQuery(this).unbind('click').click(function() {
                    cc.ui.showModalConfirm(
                            cc_resx_TR_Are_you_sure_delete_content,
                            function() {
                                jQuery('#modal-msg .msg').html(cc_resx_TR_Deleting_Content_Please_wait + '<br /><br /><img alt="' + cc_resx_TR_Please_wait + '" src="' + cc_resx_CDN_URL + 'images/ajax-loading.gif">');
                                cc.ajax.getJSON(
                                    '/myprofile/media/delete/',
                                    { mediaId: mediaId },
                                    function(resp, textStatus, XMLHttpRequest) {
                                        // Remove LI with Content:
                                        if (resp.success !== true) {
                                            // Some Server Failure or Bad Id Encountered In Processing (bad; shouldn't happen)
                                            cc.ui.showModalErrorMessage(resp.message);
                                        } else {
                                            jQuery('#media_' + mediaId).remove();
                                        }
                                    },
                                    function() {
                                        jQuery.fn.colorbox.close();
                                    }
                                );
                            },
                            function() {
                            }
                        );
                });
            });




            jQuery('.cc-edit', container).each(function() {
                var mediaId = jQuery(this).attr('cc:media');
                jQuery(this).unbind('click').click(function() {
                    jQuery('#details_' + mediaId).fadeOut(200, function() {
                        jQuery('#edit_' + mediaId).fadeIn(200, function() {
                            jQuery('#title', '#edit_' + mediaId).focus();
                        });
                    });
                });
            });




            jQuery('.cc-status-delete', container).unbind('click').click(function() {


                var statusId = jQuery(this).attr('cc:statusid');
                cc.ui.showModalConfirm(cc_resx_TR_confirm_status_delete,
                    function() {
                        cc.myprofile.statusDelete(statusId);
                        jQuery.fn.colorbox.close();
                    }, null);
                return false;
            });




            jQuery('.cc-editov', container).each(function() {
                jQuery(this).unbind('click').click(function() {
                    jQuery('.mp-mediaov-edit').fadeIn(200, function() {
                        jQuery('#info-bg', container).height(jQuery('#info', container).outerHeight());
                    });
                });
            });

            jQuery('.cc-editov-cancel', container).each(function() {
                jQuery(this).unbind('click').click(function() {
                    jQuery('.mp-mediaov-edit').fadeOut(200, function() {
                        jQuery('#info-bg', container).height(jQuery('#info', container).outerHeight());
                    });
                });
            });

            // Double Click on the entry opens the edit box:
            jQuery('.cc-edit-item', container).each(function() {
                jQuery(this).unbind('click').bind('click', function() {
                    var mediaId = jQuery(this).attr('cc:media');
                    jQuery('#details_' + mediaId).fadeOut(200, function() {
                        jQuery('#edit_' + mediaId).fadeIn(200, function() {
                            jQuery('#title', '#edit_' + mediaId).focus();
                        });
                    });
                });
            });

            jQuery('.cc-edit-cancel', container).each(function() {
                var mediaId = jQuery(this).attr('cc:media');
                jQuery(this).unbind('click').click(function() {
                    jQuery('#edit_' + mediaId).fadeOut(200, function() {
                        jQuery('#details_' + mediaId).fadeIn(200);
                    });
                });
            });

            jQuery('.cc-form-editcontent', container).unbind('submit').submit(function() {
                var mediaId = jQuery(this).attr('cc:media');
                return cc.myprofile.contentEditSubmit('#' + jQuery(this).attr('id'), mediaId);
            });

            jQuery('.cc-form-editcontent input', container).unbind('change').change(function() {
                cc.myprofile.contentEditChange('#' + jQuery(this).attr('id'));
            });

            jQuery('.cc-form-editcontent-ov', container).unbind('submit').submit(function() {
                var mediaId = jQuery(this).attr('cc:media');
                return cc.myprofile.contentEditOverlaySubmit('#' + jQuery(this).attr('id'), mediaId);
            });

            jQuery('.cc-colorbox', container).each(function() {
                var url = jQuery(this).attr('cc:href');
                url = cc.helpers.addAjaxNoCacheParam(url);
                jQuery(this).unbind('click').click(function() {
                    cc.ui.colorbox(url);
                    return false;
                });
            });

            jQuery('.cc-setfocus', container).each(function() {
                jQuery(this).unbind('click').click(function() {
                    var target = jQuery(this).attr('cc:focus');
                    jQuery(target).focus();
                    jQuery.scrollTo(target, { duration: 500, offset: { left: 0, top: -10} });
                    return false;
                });
            });

            jQuery('.cc-cam-yes', container).unbind('click').click(function() {
                var questionId = jQuery(this).attr('cc:nextQ');
                return cc.myprofile.camStartingResponse(questionId, true);
            });

            jQuery('.cc-cam-no', container).unbind('click').click(function() {
                var questionId = jQuery(this).attr('cc:nextQ');
                return cc.myprofile.camStartingResponse(questionId, false);
            });

        },

        contentEditChange: function(id) {
            jQuery('.remember', jQuery(id).parents('form:first')).css('display', 'block');
        },

        myAffiliatesShowAll: function(id) {

            jQuery('#' + id).css('overflow', 'visible');
            jQuery('.mp-showall-affs').hide();
            jQuery('.mp-hideall-affs').show();

        },

        myAffiliatesHideAll: function(id) {
            jQuery('#' + id).css('overflow', 'hidden');
            jQuery('.mp-showall-affs').show();
            jQuery('.mp-hideall-affs').hide();

        },



        zooCandyLinking: function() {
            //            cc.ajax.getJSON(
            //                    'http://cms.candycrib.com/ImageProcess.asmx/ZooCandyConnectProcessJson?cousername=brucelee&copassword=5bb221220a25dfcac0856e924e8262d6&username=animal',
            //                    {
            //                },
            //                    function(this) {
            //                        alert(this.success);
            //                        if (typeof json !== 'undefined' && typeof json.success !== 'undefined' && json.success === true) {
            //                            alert('success');
            //                        }
            //                        else {
            //                            alert('failed');
            //                        }
            //                    },
            //                    function() {

            //                    }
            //                );

        },


        WebCamScheduleCancel: function(bookingid, ismodel) {


            cc.ajax.getJSON(
                    '/webcam-scheduling-cancel/',
                    {
                        bookingid: bookingid,
                        ismodel: ismodel

                    },
                    function(resp) {
                        if (typeof resp !== 'undefined' && typeof resp.success !== 'undefined' && resp.success === true) {
                            jQuery('#c' + bookingid).hide();
                            jQuery('#u' + bookingid).css('display', 'block');
                        }
                        else {
                            cc.ui.showModalErrorMessage(cc_resx_TR_An_error_occurred_deleting);
                        }
                    },
                    function() {

                    }
                );



        },

        SetDefaultScheduleDates: function() {

            jQuery("#start_datepicker").datepicker();
            //jQuery("#start_datepicker").datepicker("option", "minDate", '+0m +0w');
            jQuery("#start_datepicker").datepicker("option", "defaultDate", '+0m +0w +1d');

            jQuery("#end_datepicker").datepicker();
            jQuery("#start_datepicker").datepicker("option", "defaultDate", '+0m +0w +8d');
            jQuery("#end_datepicker").datepicker("option", "minDate", '+0m +0w');



            //NOT TEST
            jQuery("#end_datepicker").datepicker("option", "disabled", true);


        },


        SetEndDates: function() {
            
            var selectedDate = new Date(jQuery('#end_datepicker').datepicker("getDate"));
            jQuery('#end_day').val(parseInt(selectedDate.getDate()));
            jQuery('#end_month').val(parseInt(selectedDate.getMonth()) + 1);

            jQuery('#end_year').val(parseInt(selectedDate.getFullYear()));

        },

        SetStartDates: function() {
            //var start_datepicker = jQuery('#start_datepicker').val();
            //alert(jQuery('#start_datepicker').datepicker("getDate"));



            //NOT TEST    v
            jQuery("#end_datepicker").datepicker("option", "disabled", false);


            var selectedDate = new Date(jQuery('#start_datepicker').datepicker("getDate"));

            jQuery("#end_datepicker").datepicker("option", "minDate", new Date(selectedDate));


            jQuery('#start_day').val(parseInt(selectedDate.getDate()));
            jQuery('#start_month').val(parseInt(selectedDate.getMonth()) + 1);

            jQuery('#start_year').val(parseInt(selectedDate.getFullYear()));


            selectedDate.setDate(selectedDate.getDate() + 6);

            //            //jQuery("#end_datepicker").datepicker({ maxDate: '+7d' });
            //            jQuery("#end_datepicker").datepicker("option", "maxDate", new Date(selectedDate));

        },


        WebCamScheduleInsert: function(scheduleid, year, month, timeid, changeavailability, day) {

            var target = '#webcam-schedule-layout';
            var url = '/myprofile/webcam-schedule-insert/' + scheduleid + '/' + escape(year) + '/' + escape(month) + '/' + escape(day) + '/' + timeid + '/' + changeavailability + '/';

            cc.ajax.load(target, url);

        },

        getRate: function(from, to) {

            var script = document.createElement('script');
            script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=cc.myprofile.parseExchangeRate");
            document.body.appendChild(script);
        },

        parseExchangeRate: function(data) {
            var name = data.query.results.row.name;
            var rate = (parseFloat(data.query.results.row.rate, 10) * 100);
            var scvalue = '0';
            if (jQuery('#cs-chatval').size() > 0) {
                scvalue = jQuery('#cs-chatval').val().substring(0, 5);
            }
            var stvalue = '0';
            if (jQuery('#cs-toplessval').size() > 0) {
                stvalue = jQuery('#cs-toplessval').val().substring(0, 5);
            }

            var cGBP = ((parseFloat(scvalue) / 100) * parseFloat(rate));
            var tGBP = ((parseFloat(stvalue) / 100) * parseFloat(rate));

            //THIS MONTH CAM STATS
            if (jQuery('#chatvalGBP').size() > 0) {
                document.getElementById('chatvalGBP').innerHTML = cc_resx_TR_Chat_Pay + ' = £' + cGBP.toFixed(2);
            }

            if (jQuery('#toplessvalGBP').size() > 0) {
                document.getElementById('toplessvalGBP').innerHTML = cc_resx_TR_Topless_Pay + ' = £' + tGBP.toFixed(2);
            }

            var thismonth = parseFloat(jQuery('#TotalWebCamNotIncluded').val()) + parseFloat(cGBP) + parseFloat(tGBP);

            //THIS MONTH TOTAL EARNED SO FAR
            document.getElementById('thisMonthsPayCheck').innerHTML = cc_resx_TR_Total_Earned + '  £' + parseFloat(thismonth).toFixed(2);



            //ALL TIME PAID VALUE
            var sallvalue = 0;
            if (jQuery('#WebCamAllTime').size() > 0 && jQuery('#WebCamAllTime').val() !== '') {
                sallvalue = jQuery('#WebCamAllTime').val();
            }
            var allTimeGBP = ((parseFloat(sallvalue) / 100) * parseFloat(rate));

            var allTimeWebCamNotIncluded = 0;
            if (jQuery('#AllTimeWebCamNotIncluded').val() !== '') {
                allTimeWebCamNotIncluded = jQuery('#AllTimeWebCamNotIncluded').val();

            }

            var thisAllTime = parseFloat(allTimeWebCamNotIncluded) + parseFloat(allTimeGBP);


            document.getElementById('allTimeTotalPaid').innerHTML = cc_resx_TR_mp_total_paid_to_date + ' £' + parseFloat(thisAllTime).toFixed(2);


        },



        launchEmailTemplateOverlay: function() {
            cc.ui.colorbox('/myprofile/email-template/', function() {
                // Init Response Form for Ajax Submit
                //                jQuery('#mail-form').unbind('submit').submit(function() {
                //                    return cc.userprofile.sendMailSubmit('#mail-form');
                //                });
            });
        },

        contentEditSubmit: function(formId, m) {
            var mediaId = m;
            var target = '#media_' + m;

            if (typeof cc.myprofile.postInProgress !== 'undefined' && cc.myprofile.postInProgress === true) {
                return false;
            }
            cc.myprofile.postInProgress = true;

            var form = formId;
            var submitUrl = jQuery(form).attr('action');

            jQuery('#submit').html(cc_resx_TR_Saving);
            jQuery('#submit_' + mediaId).html(cc_resx_TR_Saving);
            cc.ajax.formSubmit(
                form,
                {
                    target: target,
                    url: submitUrl
                },
                function(data, statusText) {
                    // Just updates the <li> element
                },
                function() { cc.myprofile.postInProgress = false; }
            );

            return false;
        },

        contentEditOverlaySubmit: function(formId, m) {
            var mediaId = m;
            var target = '#media_' + m;

            if (typeof cc.myprofile.postInProgress !== 'undefined' && cc.myprofile.postInProgress === true) {
                return false;
            }
            cc.myprofile.postInProgress = true;

            var form = formId;
            var submitUrl = jQuery(form).attr('action');

            jQuery('#submitov_' + mediaId).html(cc_resx_TR_Saving);
            cc.ajax.formSubmit(
                form,
                {
                    //target: target,
                    url: submitUrl
                },
                function(data, statusText) {
                    // Just updates the <li> element
                    cc.ui.colorbox(cc.helpers.addAjaxNoCacheParam('/myprofile/media/view/' + mediaId + '/'));
                    cc.myprofile.reloadPageListItem(mediaId);
                },
                function() { cc.myprofile.postInProgress = false; }
            );

            return false;
        },

        reloadPageListItem: function(mediaId) {
            var target = '#media_' + mediaId;

            var listType = 'list';
            if (jQuery('.content-list-grid').size() > 0) {
                listType = 'grid';
            }

            cc.ajax.load(target, '/myprofile/media/item/' + mediaId + '/' + listType + '/');

            return false;
        },


        enterCoverGirlComptition: function() {


            cc.ajax.getJSON(
                '/myprofile/enter-competition/',
                {},
                function(resp) {
                    if (typeof resp !== 'undefined' && resp.success === true) {
                        if (typeof resp !== 'undefined' && resp.message !== '') {
                            jQuery('#uv-left-competition').hide();
                            cc.ui.showModalOK(resp.message, '', false);
                        }
                    }
                }
            );

        },


        showEnterCompetitionMessage: function() {

            var msg = '<p class="header">Make Me a Cover Star</p><br/><a onclick="cc.myprofile.enterCoverGirlComptition();"  ><span class="button sprite">confirm</span></a><a onclick=\"jQuery.fn.colorbox.close();\"  ><span class="button sprite">no thanks</span></a><br/><a href="/competition/covergirl/">more information</a>'
            jQuery('body').append("<div style='display:none'><div id='inline-error'><div class='bg'></div><div class='enter-competition msg'></div></div></div>");


            jQuery('#inline-error .bg').css('height', '140px');
            jQuery('#inline-error .bg').css('width', '430px');
            jQuery('#inline-error').css('background-color', '#000000');
            jQuery('#cboxClose').css('background-color', '#000000');



            jQuery('#inline-error .msg').html(msg);

            jQuery.fn.colorbox({
                href: '#inline-error',
                inline: true,
                close: 'X',
                opacity: 0.65,
                onClosed: function() {
                    // If error message box initiated from qs param ?emsg=... is being closed, then 
                    // reload page without the param in the url (so it doesn't keep reappearing)
                    if (cc.helpers.getQueryStringParam('emsg') !== '') {
                        location.href = cc.helpers.stripParamFromQs('emsg');
                    }
                }
            });
        },


        camStartingResponse: function(questionId, bYes) {
            var intQ = parseInt(questionId, 10);
            var bC = true;
            // Hide anything after this response (make sure any No or Yes trees are removed)
            while (bC) {
                if (jQuery('#question-' + intQ + '-yes').size() <= 0) {
                    bC = false;
                }
                else {
                    jQuery('#question-' + intQ + '-yes').hide();
                    jQuery('#question-' + intQ + '-no').hide();
                    jQuery('#question-' + intQ + '-arrow').hide();
                }

                intQ = intQ + 1;
            }

            intQ = parseInt(questionId, 10);
            if (bYes) {
                // Show anything before this response
                for (var i = 0; i <= intQ; i++) {
                    jQuery('#question-' + i + '-arrow').show();
                    jQuery('#question-' + i + '-yes').show();
                }
            } else {
                for (var j = 0; j <= intQ; j++) {
                    jQuery('#question-' + j + '-arrow').show();
                    jQuery('#question-' + j + '-no').show();
                }
            }
        },

        blogFormValidate: function() {
            var title = jQuery('#blogTitle').val();
            if (typeof title === 'undefined' || title === '') {
                jQuery('#blogTitle').addClass('error');
                return false;
            }
            var content = tinyMCE.selectedInstance.getContent();
            if (typeof content === 'undefined' || content === '') {
                return false;
            }

            return true;
        },




        statusDelete: function(statusId) {

            cc.comments.commentDeleteInProc = true;

            // delete status
            cc.ajax.getJSON(
                '/myprofile/status/delete/',
                {
                    statusid: statusId

                },
                function(resp, textStatus) {
                    if (typeof resp !== 'undefined' && typeof resp.success !== 'undefined' && resp.success === true) {
                        location.reload(true);
                        //jQuery('#' + statusId).remove();
                    }
                    else {
                        cc.ui.showModalErrorMessage(cc_resx_TR_An_error_occurred_deleting);
                    }
                },
                function() {
                    cc.comments.commentDeleteInProc = false;
                }
            );

        },


        DeleteTwitterAccount: function() {

            cc.ui.showModalConfirm('Are you sure?',
                    function() {
                        cc.myprofile.ProcessDeleteTwitterAccount();
                        jQuery.fn.colorbox.close();
                    }, null);
        },


        ProcessDeleteTwitterAccount: function() {


            cc.ajax.getJSON(
                    '/myprofile/socialnetworks/delete-twitter/',
                    {},
                    function(resp) {
                        if (typeof resp !== 'undefined' && typeof resp.success !== 'undefined' && resp.success === true) {
                            window.location = '/myprofile/socialnetworks/';
                        }
                        else {
                            cc.ui.showModalErrorMessage(cc_resx_TR_An_error_occurred_deleting);
                        }
                    },
                    function() {

                    }
                );



        },



        blogPreview: function() {
            if (cc.myprofile.blogFormValidate()) {
                var title = jQuery('#blogTitle').val();
                var content = tinyMCE.selectedInstance.getContent();
                cc.ui.colorbox('/blogs/preview/', null, { blogTitle: title, blogEntry: content });
            }
        }

    };

} ();
