﻿// does vsworx exist? if not set empty constructor
var vsworx = vsworx ? vsworx : {};
// does vsworx.global exist? if not set empty constructor
vsworx.global = vsworx.global ? vsworx.global : {root:"/"};


// jQuery page set up routines. this function is invoked by default and does not needs speccific invocation.
$(function() {
     
    $(".linkLi").livequery('click', function() { vsworx.global.markSelectedLi(this); });
});


//includes a js file from within a js file
vsworx.global.include = function(jsFilePath) {
    
}

//changes the selected LI's class and highlights it
vsworx.global.markSelectedLi = function(el) {
    //pick up the parent object's class to find the approrpiate siblings of the clicked element
var parentClass = $(el).parent().attr("class");
    //remove the selected class from all the "li" of the clicked object's parent
$("." + parentClass + " li").removeClass("linkLiSelected");
    //apply the selected class to the clicked element.
    $(el).addClass("linkLiSelected");
    return false;
}

vsworx.global.AjaxErrorPopup = function(xmlres, mesg) {
	alert(mesg);
    return false;
}

vsworx.global.generateCSV = function(type) {
    var iframe = document.createElement("iframe");
    iframe.src = "GenerateCSV.aspx?type=" + type;
    iframe.style.display = "none";
    document.body.appendChild(iframe);
}

vsworx.global.showLoader = function(el) {
    //display different loader for blue colored backgrounds.
    var bgcolor = $(el).css("background-color");
    //_statusbar.show("bgcolor:" + bgcolor, 5000);
    if (bgcolor == "rgb(255, 255, 255)") {
        //_statusbar.show("using blue loader", 5000);
        $(el).after("<img src='/images/loading-blue.gif' class='loader' border='0' />");
    }
    else {
        //_statusbar.show("using transparent loader", 5000);
        $(el).after("<img src='/images/loading.gif' class='loader' border='0' />");
    }
    $(el).hide();
}
vsworx.global.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);
}

vsworx.global.showTooltip = function(el){
    $("#" + el.id + "+.helptip").show('normal');
}
vsworx.global.hideTooltip = function (el){
   $("#" + el.id + "+.helptip").hide('normal');
}
vsworx.global.hideError = function(){
    $(".error").hide();
}
//HIDE the Input controls on Details form and SHOW the labels in readOnly mode
vsworx.global.hideEditForm = function (containerDivId){
    $("#" + containerDivId + " input,#" + containerDivId + " select").hide();
    $("#" + containerDivId + " input:radio,#" + containerDivId + " input:checkbox").hide();
    $("#" + containerDivId + " textarea").hide();
    //anything else besides the input, etc which is supposed to be toggled based on teh form
    $("#" + containerDivId + " .formInput").hide();
    
    //the text Labels/values to be shown 
    $("#" + containerDivId + " span.fieldval").show();
    $("#" + containerDivId + " input.editButton").show();
    //$("#" + containerDivId).removeClass('addform');
    $(".btnCancel[relatedContainer='" + containerDivId + "']").hide();
    $(".btnSave[relatedContainer='" + containerDivId + "']").hide();
    $(".editButton[relatedContainer='" + containerDivId + "']").show();
}

//SHOW the Input controls in editable mode on Details form and HIDE the labels 
vsworx.global.showEditForm = function (containerDivId){
    $("#" + containerDivId + " input,#" + containerDivId + " select").show();
    $("#" + containerDivId + " input:radio,#" + containerDivId + " input:checkbox").show();
    $("#" + containerDivId + " textarea").show();
    //anything else besides the input, etc which is supposed to be toggled based on teh form
    $("#" + containerDivId + " .formInput").show();
    
    $("#" + containerDivId + " span.fieldval").hide();
    $("#" + containerDivId + ".editButton").hide();
    //$("#" + containerDivId).addClass('addform');
    $(".btnCancel[relatedContainer='" + containerDivId + "']").show();
    $(".btnSave[relatedContainer='" + containerDivId + "']").show();
    $(".editButton[relatedContainer='" + containerDivId + "']").hide();
    
    //Clear file upload
    vsworx.global.removeExtraUpload("upload","files_list");

    return false;
}
//SHOW the Form and HIDE the Data div inside the container
vsworx.global.showForm = function (containerDivId){
    $("#" + containerDivId + " .divData").hide();
    $("#" + containerDivId + " .divForm").show();
}
//HIDE the Form and SHOW the Data div inside the container
vsworx.global.hideForm = function (containerDivId){
    $("#" + containerDivId + " .divData").show();
    $("#" + containerDivId + " .divForm").hide();   
}

//invoked when user clicks on "add more details" link 
vsworx.global.showDetailFields = function() {
    //show the detail fields for the form
    $(".detailfields").show('normal');
    //hide the link for "add more details"
    $(".addDetails").hide();
};
//invoked when user clicks on "add more details" link 
vsworx.global.hideDetailFields = function() {
    //show the detail fields for the form
    $(".detailfields").hide('normal');
    //hide the link for "add more details"
    $(".addDetails").show();
};

//toggles the elements passed and also changes the text of the link passed
//THIS FUNC IS NOT COMPLETE AS ON 20.04.09
vsworx.global.customToggle = function(lnkText, togEleCsv) {
    
    //show the detail fields for the form
    $(".detailfields").hide('normal');
    //hide the link for "add more details"
    $(".addDetails").show();
};

//collapse /expand the group, change teh image and hide/show the children
vsworx.global.groupToggle = function(el){
    var groupId = $(el).attr("groupId");
    if($(el).hasClass("collapsed")){
        $(el).removeClass("collapsed");
        $(el).addClass("expanded");
        $(".groupBody[groupId=" + groupId + "]").show();
    }else{
        $(el).removeClass("expanded");
        $(el).addClass("collapsed");
        $(".groupBody[groupId=" + groupId + "]").hide();
    }
    
};
//*************************
//Close Modal  function
vsworx.global.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");  
    try{
       // Autocomplete.updateViews();
    }
    catch(err){
        //Hello
    
    } 
  
   
}

//***********************************
//FileUpload function//
var fileid=0;
var prevFile=""
vsworx.global.InitFileUpload = function(){   
    $('#divFile').after('<div id="files_list" class="uploadfilelist"></div>');
    $("input.upload").change(function(){
        vsworx.global.addfile(this,"upload","files_list");
    });
}
vsworx.global.InitFileUploadWidget = function(){   
    $('#divFileWidget').after('<div id="files_listWidget" class="uploadfilelist"></div>');
    $("input.uploadWidget").change(function(){
        vsworx.global.addfile(this,"uploadWidget","files_listWidget");
    });
}
vsworx.global.addfile=function(obj,fileClass,filelist) {

        if(fileClass=="uploadWidget")
        {
            if($(".uploadWidget").size()==2)
            {
                alert("Only one file can be uploaded.");
                $(obj).val('');
                return false;
            }
        }
        //Remove the bug in IE7
        var v = $(obj).val();
        if( v==prevFile)
        {
           $(obj).val(''); 
           prevFile="";           
           return false
        }
         prevFile=v;
        ////////////////////
       
        fileid=fileid+1;        
        $(obj).hide();
        $(obj).parent().prepend('<input type="file" id="' + fileid +'" class="' + fileClass + '" name="fileX[]" />').find("input").change(function() {vsworx.global.addfile(this,fileClass,filelist)});
        var objRE = new RegExp(/([^\/\\]+)$/);
        if(v!="")
        {
            var strName = objRE.exec(v);
            v=strName[0];
        }
        
        if(v != '') {
            $("div#" + filelist).append('<div>'+v+'<input type="button" class="remove delete floatNone" value="" /></div>')
                .find("input").click(function(){
                $(this).parent().remove();
                $(obj).remove();
                return true;
            });
        }
  }
 vsworx.global.ajaxFileUpload=function(qsParams,fileClass){
   var FileId="";
   $("." + fileClass).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;
}
vsworx.global.removeExtraUpload = function(fileClass,filelist){ 
   $("#" + filelist).html('');   
   $("." + fileClass).each(function(){
        var id=$(this).attr("id");       
        if(id!='fileUpload1')
        {
            $(this).remove();
        }
        else
        {
            $(this).show();
            $(this).val('');
            vsworx.global.addfile(this,fileClass,filelist);
        }
        ;
     });  
}

vsworx.global.ajaxAvataarUpload = function(el) {
    var FileId = $(el).attr("id");
    qsParams = "type=Avataar";
    $.ajaxFileUpload({
        secureuri: false,
        fileElementId: FileId,
        beforeSend: function() { },
        type: "GET",
        dataType: "json",
        url: "../Ajax.aspx?" + qsParams,
        complete: function() { },
        success: function(data, status) {
            $(".divimgAvataar").html('');
            $(".divimgAvataar").html("<img height='32' width='32' src='" + data.AdditionalInfo1.replace(/~/, "") + "?" + Math.random()+ "'/>");
        },
        error: function(data, status, e) { }
    })
    $(".avataarUpload").val("");
    return false;
}


    
//End FileUpload function//
//***********************************

vsworx.global.roundNumber=function(number,decimals) { // Arguments: number to round, number of decimal places
 var newString;// The new rounded number
	decimals = Number(decimals);
	if (decimals < 1) {
		newString = (Math.round(number)).toString();
	} else {
		var numString = number.toString();
		if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
			numString += ".";// give it one at the end
		}
		var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
		var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
		var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
		if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
			if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
				while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
					if (d1 != ".") {
						cutoff -= 1;
						d1 = Number(numString.substring(cutoff,cutoff+1));
					} else {
						cutoff -= 1;
					}
				}
			}
			d1 += 1;
		} 
		if (d1 == 10) {
			numString = numString.substring(0, numString.lastIndexOf("."));
			var roundedNum = Number(numString) + 1;
			newString = roundedNum.toString() + '.';
		} else {
			newString = numString.substring(0,cutoff) + d1.toString();
		}
	}
	if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
		newString += ".";
	}
	var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
	for(var i=0;i<decimals-decs;i++) newString += "0";
	//var newNumber = Number(newString);// make it a number if you like
	return newString;
};
vsworx.global.checkNumber = function(val) {
    if (val == '') {
        val = 0;
    }
    if (isNaN(val)) {
        val = 0;
    }
  
    return val;
};
