﻿var featureimage = '';
var themeId='';
var addinterphoto = '';
var divimagecheck = "<img src='..\/..\/images\/v2\/feature\/check.png\' alt=\'Check\' />";
var imageupload = "<img src='..\/..\/images\/v2\/feature\/upload.png\' alt=\'Upload\' />";
var divthumbcheck = "<img src='..\/..\/images\/v2\/feature\/check.png\' alt=\'Check\' />";
var thumbuploadlink = "<img src='..\/..\/images\/v2\/feature\/upload.png\' alt=\'Upload\' />";
var divphotocheck = "<img src='..\/..\/images\/v2\/feature\/check.png\' alt=\'Check\' />";
var photoupload = "<img src='..\/..\/images\/v2\/feature\/upload.png\' alt=\'Upload\' />";

var yoosk = {

    api: {
        ajaxBase: null,
        siteBase: null
    },

    answers: {

        rate: function(answerId, goodRating, callback) {
            /// <summary>
            /// Rates the given question.
            /// <summary>

            // Rate this question via ajax
            $.ajax({
                url: yoosk.api.ajaxBase + "rate-answer.aspx",
                type: "POST",
                data: { type: (goodRating ? "good" : "bad"), answerId: answerId },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem registering your answer rating.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback();
                }
            });
        }

    },

    questions: {

        vote: function(questionId, callback) {
            /// <summary>
            /// Votes for the given question.
            /// <summary>

            // Vote on this question (aka Yoosk it) via AJAX
            $.ajax({
                url: yoosk.api.ajaxBase + "insert-yoosk.aspx",
                type: "POST",
                data: { question: questionId },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem registering your vote.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback();
                }
            });
        },

        ask: function(publicFigureId, questionText, topicName, panelId, callback) {
            /// <summary>
            /// Submits a question as the currently logged in user (will error if not authed).
            /// <summary>

            // Vote on this question (aka Yoosk it) via AJAX
            $.ajax({
                url: yoosk.api.ajaxBase + "ask.aspx",
                type: "POST",
                dataType: "json",
                data: { to: publicFigureId, question: questionText, topic: topicName, panelId: panelId },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem submitting your question.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback(data.Id);
                }
            });
        },

        report: function(questionId, reason, email, callback) {
            /// <summary>
            /// Reports a question as breaching the terms of service.
            /// <summary>

            // Vote on this question (aka Yoosk it) via AJAX
            $.ajax({
                url: yoosk.api.ajaxBase + "report-abuse.aspx",
                type: "POST",
                data: { QuestionId: questionId, Email: email, Content: reason },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem submitting your report.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback();
                }
            });
        },

        getFormatted: function(questionId, callback) {
            /// <summary>
            /// Reports a question as breaching the terms of service.
            /// <summary>

            // Vote on this question (aka Yoosk it) via AJAX
            $.ajax({
                url: yoosk.api.ajaxBase + "get-formatted-question.aspx",
                type: "GET",
                dataType: "html",
                data: { id: questionId },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback(data);
                }
            });
        }

    },

    leaders: {

        haveRated: function(leaderId, callback) {
            /// <summary>
            /// Asks Yoosk if we have rated this leader before.
            /// <summary>

            // Call login with the given credentials
            $.ajax({
                url: yoosk.api.ajaxBase + "rate-cele.aspx",
                type: "POST",
                dataType: 'json',
                data: { action: "check", id: leaderId },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Tell the callback if we have voted or not
                    callback(data.HaveVoted);
                }
            });
        },

        rate: function(leaderId, honest, clear, informed, inspiring, consistent, intentioned, callback) {
            /// <summary>
            /// Rates the given leader
            /// <summary>

            // Call login with the given credentials
            $.ajax({
                url: yoosk.api.ajaxBase + "rate-cele.aspx",
                type: "POST",
                data: { action: "rate", id: leaderId,
                    honest: honest, clear: clear, informed: informed, inspiring: inspiring,
                    consistent: consistent, intentioned: intentioned
                },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Tell the callback if we have voted or not
                    callback();
                }
            });
        }

    },

    user: {

        // Is the current user authenticated
        isAuthenticated: false,

        login: function(username, password, rememberMe, callback) {
            /// <summary>
            /// Attempts to login to Yoosk with the given credentials.
            /// <summary>

            // Call login with the given credentials
            $.ajax({
                url: yoosk.api.ajaxBase + "user-auth.aspx",
                type: "POST",
                dataType: 'json',
                data: { username: username, password: password, rememberMe: rememberMe },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Was the login valid? Tell the callback
                    callback(data.Result);
                }
            });
        },

        register: function(username, email, password, callback) {
            /// <summary>
            /// Attempts to register a new Yoosk account.
            /// <summary>

            // Call register api
            $.ajax({
                url: yoosk.api.ajaxBase + "user-register.aspx",
                type: "POST",
                dataType: 'json',
                data: { username: username, password: password, email: email },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Was the login valid? Tell the callback
                    callback(data.Result);
                }
            });
        },

        loginWithFacebook: function(sigParams, userId, sig, callback) {
            /// <summary>
            /// Attempts to login to Yoosk using Facebook.
            /// <summary>

            // Call login with the given credentials
            $.ajax({
                url: yoosk.api.ajaxBase + "user-auth.aspx",
                type: "POST",
                dataType: 'json',
                data: { action: "FB", sigParams: sigParams, userId: userId, sig: sig },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Was the login valid? Tell the callback
                    callback(data.Result);
                }
            });
        },

        loginWithTwitter: function(username, password, callback) {
            /// <summary>
            /// Attempts to login to Yoosk using Twitter.
            /// <summary>

            // Call login with the given credentials
            $.ajax({
                url: yoosk.api.ajaxBase + "user-auth.aspx",
                type: "POST",
                dataType: 'json',
                data: { action: "Twitter", username: username, password: password },
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem accessing the Yoosk server.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Was the login valid? Tell the callback
                    callback(data.Result);
                }
            });
        }
    },

    ui: {

        textbox: {

            watermark: function(textbox, watermarkText) {
                /// <summary>
                /// Sets the default text on a textbox to change when focused, and restore if empty.
                /// </summary>

                // Grab current value to use for watermark then clear the box
                var text = $(textbox).val();
                if (watermarkText != null) text = watermarkText;
                $(textbox).val('')
                // Apply watermark
                $(textbox).watermark(text);
            }
        }
    },
    
    feature: {
         create: function( livedate, closingdate, featuretitle, featureimage, introduction ) {
            /// <summary>
            /// create a feature as the currently logged in user (will error if not authed).
            /// <summary>
            
            // Create Feature            
            $.ajax({
                url: yoosk.api.ajaxBase + "create-feature.aspx",
                type: "POST",
                dataType: "json",
                data: { livedate: livedate, closingdate: closingdate, featuretitle: featuretitle, featureimage: featureimage, introduction: introduction },
                error: function(request, status, error) {
                    alert("Sorry, there was a problem submitting your feature.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback                        
                    themeId = data.Id;
                    //callback( themeId = data.Id);
                    //yoosk.feature.sendemail(themeId);                  
                }
            });           
         },
         
         update: function( themeid, livedate, closingdate, featuretitle, featureimage, introduction)
         {
             /// <summary>
             /// update a feature as the currently logged in user (will error if not authed).
             /// <summary>
             
             //update Feature            
             $.ajax({
                url: yoosk.api.ajaxBase + "update-feature.aspx",
                type: "POST",
                dataType: "json",
                data: {themeid: themeid, livedate: livedate, closingdate: closingdate, featuretitle: featuretitle, featureimage: featureimage, introduction: introduction },
                error: function(request, status, error) {
                    alert("Sorry, there was a problem submitting your feature.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback                 
                    //callback(themeId = data.Id);
                    themeId = data.Id;
                    //yoosk.feature.sendemail(themeId); 
                }
            });      
         },
         
         
         //Upload Image
         uploadimage: function () {
         
        /*   $("#imageloading").ajaxStart(function(){
               $("#imageloading").show();
           })
           $("#imageloading").ajaxComplete(function(){
               $("#imageloading").hide(); 
               $('#imagecheck').append(divimagecheck); 
           });*/
                  
           $.ajaxFileUpload ({		   
				    url: yoosk.api.ajaxBase + "upload-image.aspx?themeId="+themeId,  
				    secureuri:false,
				    fileElementId: 'featureimage',				    
				    success: function (data, status)
				    {					   				    
					    var error='';
					    $(data).find('data').each(function() 
                        {                    
                            error = $(this).find('extensionError').text();                     
                        });
                        
                        if (error != '')
                        {
                            alert(error);
                        }
                        else
                        {
					        $(data).find('data').each(function() 
                            {   
                                featureimage = $(this).find('filename').text();
                                $('#txtFeatureImage').val(featureimage);          
                                $('#imageuploadlink').hide();
                                $("#featureimage").addClass("gray");
                                $("#featureimage").attr("disabled","disabled");                   
                                $('#imageupload').append(imageupload); 
                                $('#imagecheck').append(divimagecheck); 
                            });
                        }
				    },
				    error: function (data, status, e)
				    {
					    alert(e);
				    }   
			});
         },
         
         //Upload Image
         uploadthumbnail: function () {
     
         /*   $("#thumbloading")
            .ajaxStart(function(){
               $(this).show();
            })
            .ajaxComplete(function(){
               $(this).hide();
               $('#thumbcheck').append(divthumbcheck); 
            });*/
                                     
           $.ajaxFileUpload ({		   
				    url: yoosk.api.ajaxBase + "upload-thumbnail.aspx?themeId="+themeId,  
				    secureuri:false,
				    fileElementId: 'featurethumbnail',			  			       
				    success: function (data, status)
				    {					   				    
					    var error='';
					    $(data).find('data').each(function() 
                        {                    
                            error = $(this).find('extensionError').text();                     
                        });
                        
                        if (error != '')
                        {
                            alert(error);
                        }
                        else
                        {
					        $(data).find('data').each(function() 
                            { 
                                $('#thumbuploadlink').hide();
                                $("#featurethumbnail").addClass("gray");
                                $("#featurethumbnail").attr("disabled","disabled");                       
                                $('#thumbupload').append(imageupload);
                                $('#thumbcheck').append(divthumbcheck);    
                            });
                        }
				    },
				    error: function (data, status, e)
				    {
					    alert(e);
				    }   
			});
         },
         
         //Upload Image
         uploadphoto: function () {
         /*
            $("#photoloading")
            .ajaxStart(function(){
               $(this).show();
            })
            .ajaxComplete(function(){
               $(this).hide();
               $('#photocheck').append(divphotocheck); 
            });*/
                    
           $.ajaxFileUpload ({		   
				    url: yoosk.api.ajaxBase + "upload-photo.aspx",  
				    secureuri:false,
				    fileElementId: 'addinterphoto',			  			       
				    success: function (data, status)
				    {					   				    
					    var error='';
					    $(data).find('data').each(function() 
                        {                    
                            error = $(this).find('extensionError').text();                     
                        });
                        
                        if (error != '')
                        {
                            alert(error);
                        }    
                        else
                        {
					        $(data).find('data').each(function() 
                            {   
                                addinterphoto = $(this).find('filename').text();
                                $('#txtFeatureImage').val(addinterphoto);          
                                $('#photouploadlink').hide();
                                $("#addinterphoto").addClass("gray");
                                $("#addinterphoto").attr("disabled","disabled");                                              
                                $('#photoupload').append(photoupload); 
                                $('#photocheck').append(divphotocheck);
                            });
                        }
				    },
				    error: function (data, status, e)
				    {
					    alert(e);
				    }   
			});
         },
         emailme: function (chkmail , callback) {
            /// <summary>
            /// Email me about upgrading to a premium account.
            /// <summary>
            $.ajax({
                url: yoosk.api.ajaxBase + "update-user-emailme.aspx",
                type: "POST",
                data: { chkmail: chkmail},
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem Email me about upgrading to a premium account.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback();
                }
            });
         },
         
         sendemail: function (themeId, callback ) {            
            /// <summary>
            /// Send email to admin that noticate approve Feature.
            /// <summary>
              $.ajax({
                url: yoosk.api.ajaxBase + "send-email.aspx",
                type: "POST",
                data: {themeid: themeId},           
                // Handle error event
                error: function(request, status, error) {
                    alert("Sorry, there was a problem Email to Admin.");
                },
                // Handle all finished OK event
                success: function(data, status, request) {
                    // Call the callback
                    callback();
                }
            });
         },
         
         visiblefield: function () {
            
            $("#occupation").addClass("gray");
            $("#addinterphoto").addClass("gray");
            $("#links").addClass("gray");
            $("#occupation").attr("disabled","disabled");
            $("#addinterphoto").attr("disabled","disabled");
            $("#links").attr("disabled","disabled");            
            $("#photouploadlink").hide();
            $('#photoupload').append(photoupload); 
         },
        
         resetfiled :function ()
         {
             $("#_hidden1").val("");
             $("#_input1").val("");
             $("#occupation").val("");             
             $("#occupation").removeAttr("disabled");
             $("#occupation").removeClass("gray");
             $("#links").val("http://");
             $("#links").removeAttr("disabled");
             $("#links").removeClass("gray");             
             $("#addinterphoto").val("");
             $("#addinterphoto").removeAttr("disabled");  
             $("#addinterphoto").removeClass("gray");   
              
             $('#photouploadlink').show();
             $('#photoupload').html("");
             $('#photocheck').html("");
         },
         
         resetfieldtype: function() 
         {
            $("#occupation").removeAttr("disabled");
            $("#occupation").removeClass("gray");
            $("#links").removeAttr("disabled");
            $("#links").removeClass("gray");
            $("#addinterphoto").removeAttr("disabled");  
            $("#addinterphoto").removeClass("gray");     
            $('#photouploadlink').show();
            $('#photoupload').html("");  
         }                
    }

};
