﻿$(function() {
    $.ajaxSetup({
        error: function(xhr, msg) { alert(msg) },
        type: "POST",
        url: "/Ajax.aspx"
    });

    $("#btnSignUp").livequery('click', function(el) { signUp(this); });
    $(".watermark").livequery('focus', function(el) { wmFocus(this); });
    //$(".watermark").livequery('blur', function(el) { wmBlur(this); });
    $(".watermark").blur(function() {
        //if the current vaue matches the value in title, it means its watermark value
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
            $(this).addClass("watermark");
        }
    });

    if ($(".textbox").val() == $(".textbox").attr("title")) {
        $(".textbox").addClass("watermark");
    }
    $(".txtUserName").livequery('blur', function(el) { checkUserName(this); });
    $(".txtUrl").livequery('blur keyup', function(el) { checkSubDomain(this); });
    $(".btnSignUp").livequery('click', function(el) { return checkSignupValidation(); });
    $(".btnActivate").livequery('click', function(el) { return checkActivateValidation(); });
    $(".btnFeedback").livequery('click', function(el) { return saveFeedback(this); });

    $(".fbTypeTabs>li").livequery('click', function(el) { showFbTypeForm(this); });
    //binding for filtering Feedback
    $("a[st]").livequery('click', function(el) { getFeedback(this); });
     //binding for filtering Feedback
    $("a.customPaging").livequery('click', function(el) { getFeedback(this); });
    
    $("#btnSaveComment").livequery('click', function(el) { saveFeedbackComment(this); });
    $("#aspnetForm").livequery('keydown', function(el) { if (el.keyCode == 13) { return checkActivateValidation(); } });

    //****Custom Drop down bindings : START
    //toggle the custom drop down options on
    $(".btnCustomDropdown").livequery('click', function(el) {
        //hide all teh csutom drop downs except eth clciked ones
        $("ul.customDropdown[id!='" + $(this).attr("relId") + "']").hide();
        //removing the active class from all teh buttons except teh clicked one
        $("a.btnCustomDropdown[relId!='" + $(this).attr("relId") + "']").removeClass("active");
        //shwo the clicked dropdown options now
        $("ul.customDropdown[id='" + $(this).attr("relId") + "']").toggle(); $(this).toggleClass("active"); $("ul.customDropdown li[optionValue='" + $(this).attr("selectedOptionValue") + "']").hide();
    });
    //any option being clicked in Custom drop down
    $("ul.customDropdown li").livequery('click', function(el) { customDropdownClick(this); });
    //****Custom Drop down bindings : END
    $(".lnkChangeStatus").livequery('click', function(el) { $("#liStatus" + $(this).attr("fbId")).toggle(); });
    $(".lnkCancelChangeStatus").livequery('click', function(el) { $("#liStatus" + $(this).attr("fbId")).hide(); });
    $(".btnChangeStatus").livequery('click', function(el) { updateFeedbackStatus(this); });
    $(".lnkDeleteFeedback").livequery('click', function(el) { deleteFeedback(this); });
    $(".lnkDeleteFeddbackComment").livequery('click', function(el) { deleteFeedbackComment(this); });
});
deleteFeedbackComment=function(el){
    if(! confirm("Are you sure to delete this comment")){
        return;
    }
     var commentId = $(el).attr("commentId");
     $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'DeleteFeedbackComment', commentId: commentId},
        success: function(msg) {
           $("li.CommentContent[commentId=" + commentId + "]").remove();
        },
        complete: function() { hideLoader($(el)); }
    });
    
};
deleteFeedback=function(el){
    if(! confirm("Are you sure to delete this feedback")){
        return;
    }
     var fbid = $(el).attr("fbId");
     $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'DeleteFeedback', fbid: fbid},
        success: function(msg) {
           $("li.fbForumContent[fbid=" + fbid + "]").remove();
        },
        complete: function() { hideLoader($(el)); }
    });
    
};
customDropdownClick = function(el) {
    var selValue = $(el).attr("optionValue");
    var forParam = $(el).parents("ul:first").attr("forParam");
    //alert(forParam);
    switch (forParam.toLowerCase()) {
        //when teh admin user updates the status of any feedbakc  
        case "feedbackstatus":
           // $("#hdnFbStatus").val(selValue);
            break;
        case "feedback":
            var url = vsworx.global.root + 'projects/overview.aspx?pid=' + selValue;
            //alert(url);
            window.location.href = url;
            break;
    }
};
updateFeedbackStatus=function(el){
   var fbid = $(el).attr("fbId");
   var selectedTab=$(".fbForumTabs").find("li.selected").find("a").attr("st");
   var pageindex=1;
    if( $("a.customPaging").length>0){
        pageindex=$("a.active[PageIndex]").attr("PageIndex");
    }
   var type= $(".hdnFeedbackType").val(); 
   var comment=$("#txtComment" + fbid).val();
   var status=$("#cmbChangeStatus" + fbid).val();
   $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'UpdateFeedbackStatus', fbid: fbid, status: status,selectedTab:selectedTab,pageindex:pageindex,type:type,comment:comment},
        success: function(msg) {
            var data = JSON.parse(msg);  
            $("#divFeedbackList").replaceWith(data.HTML); 
        },
        complete: function() { hideLoader($(el)); }
    });
};
saveFeedbackComment = function(el) {
    var fbid= $(el).attr("fbid");
    var comment= $("#txtComment").val();    
     $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'SaveFeedbackComment', fbid: fbid, comment: comment},
        success: function(msg) {
           var data = JSON.parse(msg);       
            $("#commentlist").replaceWith(data.HTML);
            $("#txtComment").val("");  
        },
        complete: function() { hideLoader($(el)); }
    });
    return false;
}
getFeedback = function(el) {
    var type= $(".hdnFeedbackType").val();
    var pageindex=1;
    if( $("a.customPaging").length>0){
        pageindex=$("a.active[PageIndex]").attr("PageIndex");
    }
    if($(el).attr("PageIndex")!=null){
         pageindex=$(el).attr("PageIndex");
    } 
    if($(el).attr("st")!=null){
        $(".fbForumTabs").find("li").removeClass("selected");
        $(el).parents("li").addClass("selected");
    }
    var selectedTab=$(".fbForumTabs").find("li.selected").find("a").attr("st");
    el=$("#spanLoding");
     $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'GetFeedback', type: type, pageindex: pageindex,selectedTab:selectedTab},
        success: function(msg) {
           var data = JSON.parse(msg);  
            $("#divFeedbackList").replaceWith(data.HTML);
        },
        complete: function() { hideLoader($(el)); }
    });
    return false;
}
showFbTypeForm = function(el) {
    //remove teh selected class
    $(".fbTypeTabs>li").removeClass("selected");
    //pick up the bg class of clicked item
    var selBgClass = $(el).attr("class");
    var captionText = $("li." + selBgClass + " span").text();
    var type=$(el).attr("type");
    $("label.fbHelpCaption").text(captionText);
    //add selected class to clicked item
    $(el).addClass("selected");
    //apply the selected class to eth form
    $("ul#fbForm").attr("class", selBgClass);
    $(".btnFeedback").attr("feedbacktype",type)
}
ajaxFileUpload=function(qsParams){
   var FileId="";     
   qsParams=qsParams 
        
   $(".upload").each(function(){
       FileId=$(this).attr("id");        
       $.ajaxFileUpload
	   ({
			secureuri:false,
			fileElementId:FileId,			
			beforeSend:function(){},
			type: "GET",
			url: "Ajax.aspx?" + qsParams,
			complete:function(){},				
			success: function (data, status){
			                 
			                  },
			error: function (data, status, e){}
		}
	)
   });    
   return false;
}
checkFeedbackValidation=function(){  
    vsworx.validator.clearRules();
    vsworx.validator.rules = ["txtFeedbackTitle:required:Please enter Title.", "txtFeedbackTitle:maxlength[255]:max 255 charecter allow.", 
                               "txtFeedbackDescription:required:Please enter Description."];
    vsworx.validator.errorContainer = ".formMessage";  
    vsworx.validator.validate(); 
    return (vsworx.validator.failedElements.length == 0);
}
saveFeedback=function(el){
    if(checkFeedbackValidation()==false) return false;  
    var type=$(".btnFeedback").attr("feedbacktype");
    var title=$("#txtFeedbackTitle").val();
    var desc=$("#txtFeedbackDescription").val();
    var tag=$("#txtFeedbacktag").val();
    var subdomain=$("#hdnSubDomain").val();
    var uname=$("#hdnUser").val();
     $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'SaveFeedback', type: type, title: title,desc:desc,tag:tag,subdomain:subdomain,uname:uname },
        success: function(msg) {
           var data = JSON.parse(msg);
            ajaxFileUpload("fbId=" + data.AdditionalInfo1);
            alert(data.Message);
            document.forms[0].reset();
        },
        complete: function() { hideLoader($(el)); }
    });
}
//Close Modal Popup function
closeModalPopup = function(popupId, callbackFn){   
    $("div#" + popupId).slideUp('slow', function() {
        $("div#modalContainer").fadeOut('fast', function() {
            $("div#modalOverlay").fadeOut('fast', function() {
                $.modal.close();
            }); // close overlay
        }); // close container
    }); // close popup holder
    if ($.isFunction(callbackFn)) {
        callbackFn.apply();
    }
    $("body").css("cursor:default");
}
//check input validtion
checkSignupValidation=function(){
    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".txtFirstName").attr("id") + ":required:Please enter First Name.", $(".txtFirstName").attr("id") + ":maxlength[100]:max 100 charecter allow for First Name.",
                              $(".txtLastName").attr("id") + ":required:Please enter Last Name.", $(".txtLastName").attr("id") + ":maxlength[100]:max 100 charecter allow for Last Name.",
                              $(".txtEmail").attr("id") + ":required:Please enter Email.", $(".txtEmail").attr("id") + ":maxlength[200]:max 200 charecter allow for Email.",$(".txtEmail").attr("id") + ":email:Please enter valid Email.",
                              $(".txtPassword").attr("id") + ":password:The password must be at least 6 characters long. Allow charecters alphanumeric or any of these special characters (~!@#$%^&()+~?*=_-) only.", "txtPassword:maxlength[50]:max 50 charecter allow for Password.", $(".txtPassword").attr("id") + ":maxlength[50]:max 50 charecter allow for Password.",
                              $(".txtConfirmPassword").attr("id") + ":required:Please enter Confirm Password.",
                              $(".txtCompanyName").attr("id") + ":required:Please enter Company Name.", $(".txtCompanyName").attr("id") + ":maxlength[255]:max 255 charecter allow for Company Name." ,
                              $(".txtPassword").attr("id") + ":comparepassword[" + $(".txtConfirmPassword").val() + "]:Password mismatch." ];
    
    // $(".txtUserName").attr("id") + ":required:Please enter User Name.", $(".txtUserName").attr("id") + ":maxlength[50]:max 50 charecter allow for User Name.",$(".txtUserName").attr("id") + ":minlength[5]:Please enter atleast 5 charecter for User Name.",
    vsworx.validator.errorContainer = "#divErrorMsg";
    vsworx.validator.validate();   
    return (vsworx.validator.failedElements.length == 0);

}
checkActivateValidation=function(){
    var e1;
    //checkSubDomain(e1);
    vsworx.validator.clearRules();
    vsworx.validator.rules = [$(".txtUrl").attr("id") + ":required:Please enter Url.", $(".txtUrl").attr("id") + ":maxlength[100]:max 100 charecter allow.",$(".txtUrl").attr("id") + ":domain[" + $(".txtUrl").val() + ".breezepm.com]:Invalid domain." ];
    vsworx.validator.errorContainer = ".formMessage";
     vsworx.validator.validate();
     if($("#hdnUrl").val()!=""){         
        return false;
      }
     return (vsworx.validator.failedElements.length == 0);
}
//main signup function
signUp = function(el) {
    var uname = $("#txtname").val();
    var email = $("#txtemail").val();
    $.ajax({
        beforeSend: function() { showLoader($(el)); },
        data: { method: 'SignUp', name: uname, email: email },
        success: function(msg) {
            var data = JSON.parse(msg);
            if (data.IsValid == true) {
                $("ul.signupform").empty().append("<li>Thanks for signup, we shall send you an email as soon we launch</li>");
            }
        },
        complete: function() { hideLoader($(el)); }
    });

}
//watermark function called on focus of the textbox
wmFocus = function(el) {
    //if the current vaue matches the value in title, it means its watermark value
    if($(el).val() == $(el).attr("title")) {
        $(el).val("");
        $(el).removeClass("watermark");
    }
}
//watermark function called on Blur of the textbox
wmBlur = function(el) {
    //alert("hi:");
    alert($(el).val());
    //if the current vaue matches the value in title, it means its watermark value
    if ($(el).val() == "") {
        $(el).val($(el).attr("title"));
        $(el).addClass("watermark");
    }
}

showLoader = function(el) {
    $(el).after("<img src='/images/loading.gif' class='loader' border='0' />");
    $(el).hide();
}
hideLoader = function(el) {
    $("img.loader").remove();
    $(el).show();    
    //hide ANY display message which has the class fadeaway. this is useful when teh success messgae needs
    // to be shown to the user and then automatically removed.
    window.setTimeout(function() { $('.fadeaway').hide('normal'); }, 2000);
}

checkUserName=function(e1)
{
    var uname = $(".txtUserName").val(); 
    $("#userexist").html("");   
    $.ajax({
        beforeSend: function() {  },
        data: { method: 'CheckUserName', name: uname},
        success: function(msg) {
            var data = JSON.parse(msg);
            if (data.IsValid == false) {
                $("#userexist").html("User already exist");                
            }
        },
        complete: function() {  }
    });
    
}
checkSubDomain = function(e1) {
    var dname = $.trim($(".txtUrl").val());
    if (dname == '') return;
    $("#urlexist").html("");
    $("#hdnUrl").val('');
    $.ajax({
        beforeSend: function() { },
        data: { method: 'CheckSubDomain', dname: dname },
        success: function(msg) {
            var data = JSON.parse(msg);
            if (dname != '') {
                if (data.IsValid == false) {
                    $("#urlexist").text("Sorry ! the name selected by you is Not Available").removeClass("formMessage").addClass("error");
                    $("#hdnUrl").val(dname);                   
                    $(".btnActivate").attr("disabled","disabled");
                }
                else {
                    $("#urlexist").text("Congratulations ! the name selected by you is Available.").removeClass("error").addClass("formMessage");
                    $(".btnActivate").removeAttr("disabled");
                }
            }
        },
        complete: function() { }
    });
}
