﻿//AbuseFunctions.js
// THE FUNCTION THAT REPORTS ABUSE 
function funcSendAbuseReport()
{
    var RepAbuseAJAX = new JeeranRemoteScripting();
	RepAbuseAJAX.SetRequestMethod("POST");
	RepAbuseAJAX.SetRequestURL(AjaxAbuseUrl);
	RepAbuseAJAX.SetData("FileID=" + FileID + "&action=report");
		
	RepAbuseAJAX.SetRequestAsynch(true);
    RepAbuseAJAX.InitializeRequester();
    ShowDiv('tabLoadingSendAbuseReport');
	RepAbuseAJAX.SendRequest();

	RepAbuseAJAX.OnLoaded = function() {
	    //HideDiv('pnlReportAbuseForm');
	    ShowDiv('DivReportAbuseSuccess');
        document.getElementById('DivReportAbuseSuccess').innerHTML = RepAbuseAJAX.GetText();
        HideDiv('tabLoadingSendAbuseReport');
	    RepAbuseAJAX = null;
	}
	
	RepAbuseAJAX.OnFailure = function() {
	        RepAbuseAJAX = null;
	        HideDiv('tabLoadingSendAbuseReport');
	        document.getElementById('DivReportAbuseSuccess').innerHTML = "Failure";
	}
}

//admin.js
var IdaraFeatureIcon = '/im/j2/fam/png/bell_add.png';
var IdaraUnFeatureIcon = '/im/j2/fam/png/bell_delete.png';

function Feature(FileID) {
    
    var myAjaxRequester = CreateAjaxRequest(IdaraAjaxUrl, "POST", "fileid=" + FileID + "&action=feature");
    
    myAjaxRequester.OnLoaded = function () {
        if (myAjaxRequester.GetText() == "featured")
        {
            alert("This video has been ADDED to the featured list!");
        }
        else        
        {
            alert("Failure");
        }
    }
    
    myAjaxRequester.OnFailure = function () {
        alert("Failure");
        
    }   
}

function UnFeature(FileID) {
    
    var myAjaxRequester = CreateAjaxRequest(IdaraAjaxUrl, "POST", "fileid=" + FileID + "&action=unfeature");
    
    myAjaxRequester.OnLoaded = function () {
        if (myAjaxRequester.GetText() == "unfeatured")
        {
            alert("This video has been REMOVED from the featured list!");
        }
        else        
        {
            alert("Failure");
        }
    }
    
    myAjaxRequester.OnFailure = function () {
        alert("Failure");
        
    }   
}

function Delete(FileID) {
    if(window.confirm("Are you sure you wish to delete this video?"))
    {
        var myAjaxRequester = CreateAjaxRequest(IdaraAjaxUrl, "POST", "fileid=" + FileID + "&action=delete");
        
        myAjaxRequester.OnLoaded = function () {
            if (myAjaxRequester.GetText() == "deleted")
            {
                alert("This video has been DELETE!");
            }
            else        
            {
                alert("Failure");
            }
        }
        
        myAjaxRequester.OnFailure = function () {
            alert("Failure");        
        }
    }       
}

function ReConvert(FileID) {
    if(window.confirm("Are you sure you wish to Re-Convert this video?"))
    {
        var myAjaxRequester = CreateAjaxRequest(IdaraAjaxUrl, "POST", "fileid=" + FileID + "&action=reconvert");
        
        myAjaxRequester.OnLoaded = function () {
            if (myAjaxRequester.GetText() == "converted")
            {
                alert("This video has been Re-Converted!");
            }
            else        
            {
                alert("Failure");
            }
        }
        
        myAjaxRequester.OnFailure = function () {
            alert("Failure");        
        }
    }       
}

//BlogIt.js
function SelectInput(Input) {
    var Control = j$Obj(Input); 
    Control.focus();
}
function SelectLayout(Layout, Snapshot)
{
    // Reset borders
    for(var i=1; i <= TotalLayouts; i++)
    {
        j$Obj("Layout"+i).style.border = "0";
    }
    
    // Set new border    
    j$Obj(formPostLayout).value = Layout;
    Snapshot.style.border = "3px solid #ccf";
}

//FileSettings.js

function HideDiv(DivName) 
{
document.getElementById(DivName).style.visibility = "hidden";
document.getElementById(DivName).style.display = "none";
}
function ShowDiv(DivName) 
{document.getElementById(DivName).style.visibility = "visible";
document.getElementById(DivName).style.display = "";
}


function funcSaveFileSettings(FileID) {
    if (ValidateFileTD(FileID))
    {
        funcSetFileTD(FileID,document.getElementById('formFileTitle_' + FileID).value, document.getElementById('formFileDescription_' + FileID).value, 'title')
    }
}

function DisplaySetFileSettingsSuccess(FileID, myhtml) {
funcCancelFileSettings(FileID);
document.getElementById('spanFileSetSettingsSuccess_' + FileID).innerHTML = myhtml;
ShowDiv('spanFileSetSettingsSuccess_' + FileID);
}


// FUNCTION THAT CALLS DOES FORM VALIDATION  - OmarAA
function ValidateForm(elValue, errForm, regexFormVld, arrFormRange, errregexFormReq, errregexFormVld, errregexFormRange)
{
        document.getElementById(errForm).innerHTML = "";
        
        var validated = true;
        var errValue = "";

        if (arrFormRange[0] != 0)
        {
            // CHECK IF FORM IS EMPTY OR NULL - OmarAA
            if(elValue == null || elValue == "") {
                   validated = false;
                   errValue += document.getElementById(errregexFormReq).value;
            }
        }

        if (validated == true) {
            // VALIDATE FORM - OmarAA
            
            var regexValue= document.getElementById(regexFormVld).value;        
            var re = new RegExp(regexValue);         
            if(!elValue.match(re))
            {
                   validated = false;
                   errValue += document.getElementById(errregexFormVld).value;
            }
            
            // VALIDATE LENGTH - OmarAA
            if ((elValue.length < arrFormRange[0]) || (elValue.length > arrFormRange[1]))
            {
                   validated = false;
                   errValue += document.getElementById(errregexFormRange).value;
            } 
        }
        
        // IF VALIDATED DO WORK USING AJAX, IF NOT THEN SHOW ERROR MESSAGE - OmarAA
        if(validated == true) {
            return true;
            document.getElementById(errForm).innerHTML = "";
        } else {
           document.getElementById(errForm).innerHTML = errValue;
           return false;
        }
} 

function ValidateFileTD(FileID) {


// GET FORM VALUE - OmarAA
var elValueTitle = document.getElementById('formFileTitle_' + FileID).value;
var elValueDescr = document.getElementById('formFileDescription_' + FileID).value;

var ValidTitle = ValidateForm(elValueTitle,'errformFileTitle_'+FileID,'RegExvldFileTitle', new Array("3", "200"),'vldFileTitleErrRequired','vldFileTitleErr','vldFileTitleErrRange');
var ValidDescription = ValidateForm(elValueDescr,'errformFileDescr_'+FileID,'RegExvldFileDescr',new Array("0", "500"),'vldFileDescrErrRequired','vldFileDescrErr','vldFileDescrErrRange');

if (ValidTitle && ValidDescription)
    { return true; }
else
    { return false; }

}

//FormsValidation.js
  function CheckFileTitle()
      {
           txtTitleID = document.getElementById(Title);
            
            var isValid = true;
            
            var lblTitleTextRequiredID = document.getElementById('lblTitleTextRequired');
            var lblFileTextRangeID = document.getElementById('lblFileTextRange');
            var lblTitleContainsBadCharID  = document.getElementById('lblTitleContainsBadChar');
           
            lblTitleTextRequiredID.style.display = "none"
            lblTitleContainsBadCharID.style.display = "none";
            lblFileTextRangeID.style.display = "none";
            (txtTitleID).style.border = '1px solid #ccc';
                                       
            var titleText = txtTitleID.value;
            titleText = titleText.replace(/(^\s+)(\s+$)/, "");
            
            if((titleText == '') || (titleText == null))
            {
                (txtTitleID).style.border = '1px solid red';
                lblTitleTextRequiredID.style.display = "block";
                isValid = false;
            }
            else
            {
              //strip HTML tags
              titleText = stripHTMLTags(titleText);
             
              if(ContainsBadChars(titleText) == true)
              {
                (txtTitleID).style.border = '1px solid red';
                lblTitleContainsBadCharID.style.display = "block";
                isValid = false;
              }
                 
              txtTitleID.value = titleText;
              
              //Testing the range.
              if((titleText.length > 50) || (titleText.length < 3))
              {
                (txtTitleID).style.border = '1px solid red';
                lblFileTextRangeID.style.display = "block";
                isValid = false;
              }   
            }
            
            return isValid;
      }
      
      function CheckFileDesc()
      {
            var isValid = true;
            
            txtDescriptionID = document.getElementById(Desc);
            
            var lblDescriptionTextRangeID = document.getElementById('lblDescriptionTextRange');
            var lblDescriptionTextRequiredID = document.getElementById('lblDescriptionTextRequired');
            var lblDescriptionContainsBadCharID = document.getElementById('lblDescriptionContainsBadChar');
          
            lblDescriptionTextRequiredID.style.display = "none";
            lblDescriptionContainsBadCharID.style.display = "none";
            lblDescriptionTextRangeID.style.display = "none";
            (txtDescriptionID).style.border = '1px solid #ccc';
                                       
            var descText = txtDescriptionID.value;
            descText = descText.replace(/(^\s+)(\s+$)/, "");
                        
            if((descText == '') || (descText == null))
            {
                (txtDescriptionID).style.border = '1px solid red';
                lblDescriptionTextRequiredID.style.display = "block";
                isValid = false;
            }
            else
            {
              //strip HTML tags
              descText = stripHTMLTags(descText);
              
              if(ContainsBadChars(descText) == true)
              {
                (txtDescriptionID).style.border = '1px solid red';
                lblDescriptionContainsBadCharID.style.display = "block";
                  isValid = false;
              }
              
              txtDescriptionID.value = descText;
              
              //Testing the range.
              if((descText.length > 400) || (descText.length < 3))
              {
                (txtDescriptionID).style.border = '1px solid red';
                lblDescriptionTextRangeID.style.display = "block";
                  isValid = false;
              }   
            }
            
            //isValid = false;
            return isValid;
      }
      
      function ValidateCategory()
      {
          var isValid = true; 
          var categoryList = document.getElementById(lstCategoriesID);
          var dropdownIndex = categoryList.value;

          document.getElementById("lblVldCategory").style.display = "none";
         (categoryList).style.border = '1px solid #ccc';
                      
          //check whether the user chose a category type or not.
          if(dropdownIndex == 0)
          {    
             document.getElementById("lblVldCategory").style.display = 'block';
             (categoryList).style.border = '1px solid red';

            isValid = false;
          }
          
          return isValid;
      }
      
      function ContainsBadChars(Text)
      {
        var regexValue= document.getElementById('RegExvldFileTitle').value;        
        var re = new RegExp(regexValue);         
       
        if(!Text.match(re) == false)
        {
            return false;
        }
        else
        {
            return true;
        }
      }
      
      
    function ValidateFileExt()
    {
        var isValid = true;
        var file = document.getElementById(fileUploader);
        var fileName = file.value;
        
        document.getElementById("lblErrFileEmpty").style.display = "none";
        document.getElementById("lblErrExt").style.display = "none";
        (file).style.border = '1px solid #ccc';
         
        if((fileName == '') || (fileName == null))
        {

            document.getElementById("lblErrFileEmpty").style.display = 'block';
            isValid = false;
        }
        else
        {
           //Check the extension of the file 
           var ext = fileName.slice(fileName.lastIndexOf(".")).toLowerCase();
           ext = ext.split(".");
             
           if(FileExtensions.indexOf(ext[1]) == -1)
           {
             document.getElementById("lblErrExt").style.display = 'block';
            (file).style.border = '1px solid red';
            isValid = false;
           }
         }
         
        return isValid;
    }  
      
    function ValidateForms()
    {
        var isValidTitle;
        var isValidDesc;
        var isValidCat;
        var isValidExt;
        
        isValidTitle = CheckFileTitle();
        isValidDesc = CheckFileDesc();
        isValidCat = ValidateCategory();
        isValidExt = ValidateFileExt();
        
        if((isValidTitle)&&(isValidDesc)&&(isValidCat)&&(isValidExt))
        {
           return true;
        }
        else
        {
            return false;
        }
        
    }
    
//ImageUploader.js
var imageUploader1 = null;
var uniqueId = 0;
var prevUploadFileCount = 0;
var dragAndDropEnabled = true;


var allowDrag = false;

function fullPageLoad(){
	imageUploader1 = getImageUploader("ImageUploader1");

//	var UploadPane=document.getElementById("UploadPane");
//	
//	while (UploadPane.childNodes.length > 0){
//		UploadPane.removeChild(UploadPane.childNodes[0]);
//	}

	//Fix Opera applet z-order bug
	if (__browser.isOpera){
		UploadPane.style.height = "auto";
		UploadPane.style.overflow = "visible";
	}


	//Handle drag & drop.
	if (__browser.isIE || __browser.isSafari){
		var target = __browser.isIE ? UploadPane : document.body;
		target.ondragenter = function(){
			var e=window.event;
			var data = e.dataTransfer;
			if (data.getData('Text')==null){
				this.ondragover();
				data.dropEffect="copy";
				allowDrag=true;
			}
			else{
				allowDrag=false;
			}
		}
		
		target.ondragover=function(){
			var e = window.event;
			e.returnValue = !allowDrag;
		}

		target.ondrop = function(){
			var e = window.event;
			this.ondragover();
			e.dataTransfer.dropEffect = "none";
			processDragDrop();
		}
	}
	else {
		window.captureEvents(Event.DRAGDROP);
		window.addEventListener("dragdrop", function(){
				processDragDrop();
			}, true);
	}

}

function processDragDrop(){
	alert("Adding files with drag & drop can not be implemented in standard version due security reasons. However it can be enabled in private-label version."+
		"\r\n\r\nFor more information please contact us at sales@aurigma.com");
	if (imageUploader1){
		//imageUploader1.AddToUploadList();
	}
}

//To identify items in upload list, GUID are used. However it would work 
//too slow if we use GUIDs directly. To increase performance, we will use 
//hash table which will map the guid to the index in upload list. 

//This function builds and returns the hash table which will be used for
//fast item search.
function getGuidIndexHash(){
	var uploadFileCount = imageUploader1.getUploadFileCount();
	var guidIndexHash = new Object();
	for (var i = 1; i <= uploadFileCount; i++){
		guidIndexHash["" + imageUploader1.getUploadFileGuid(i)] = i;
	}
	return guidIndexHash;
}

//This function returns HTML which represent the single item in the custom upload pane.
//It contains of the Thumbnail object and form elements for each piece of data (in our 
//case - title and description). If you want to upload extra data, you should write
//additional form elements here.
//
//It is highly recommended not to copy this function into the main HTML page to 
//avoid problems with activation of ActiveX controls in Internet Explorer with
//security update 912945. You can read more detailed about activation on Microsoft website:
//
//http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/activating_activex.asp 
function addUploadFileHtml(index){
	var guid = "" + imageUploader1.getUploadFileGuid(index);
	var fileName = "" + imageUploader1.getUploadFileName(index);

	var h = "<table cellspacing=\"5\"><tbody>";
	h += "<tr>";
	h += "<tr><td colspan='2' align='right'><b><a href=\"#UploadPane\" onclick=\"return Remove_click('" + guid + "');\">x</a></b></td></tr>";
	h += "<td class=\"Thumbnail\" align=\"center\" valign=\"top\">";

	//Add thumbnail control and link it with Image Uploader by its name and GUID.
	var tn = new ThumbnailWriter("Thumbnail" + uniqueId, 96, 80);
	//Copy codebase and version settings from ImageUploaderWriter instance.
	tn.activeXControlCodeBase = iu.activeXControlCodeBase;
	tn.activeXControlVersion = iu.activeXControlVersion;
	tn.javaAppletCodeBase = iu.javaAppletCodeBase;
	tn.javaAppletCached = iu.javaAppletCached;
	tn.javaAppletVersion = iu.javaAppletVersion;

	tn.addParam("ParentControlName", "ImageUploader1");
	tn.addParam("Guid", guid);
	tn.addParam("FileName", fileName);
	h += tn.getHtml();

	h += "</td></tr><tr>";
	h += "<td valign=\"top\">";

	
	//Add Title element.
	h += "<span style=\"color: red;\">*&nbsp;</span>" + fileTitleText + "<br />";
	h += "<input id=\"fileTitle" + uniqueId + "\" class=\"Title\" type=\"text\" />";
	h += "<label class=\"alert\" id=\"errMsgFileTitle" + uniqueId + "\"></label><br /><br />";

	//Add Description element.
	h += "<span style=\"color: red;\">*&nbsp;</span>" + fileDescriptionText + "<br />";
	h += "<textarea id=\"fileDescription" + uniqueId + "\" class=\"Description\"\"></textarea>";
	h += "<label class=\"alert\" id=\"errMsgFileDescription" + uniqueId + "\"></label><br><br />";

	//Add Tags element.
	h += fileTagsText + "<br />";
	h += "<input id=\"fileTags" + uniqueId + "\" class=\"Title\" type=\"text\" /><br />";
	h += "<small><span>" + fileTagsMsgText + "</span></small><br /><br />";

	//Add Privacy element.
	h += filePrivacyText + "<br />";
	h += "<input type=\"radio\" value=\"1\" name=\"filePrivacy" + uniqueId + "\" id=\"filePrivacy" + uniqueId + "\"/>" + everyoneText + "<br />";
	h += "<input type=\"radio\" value=\"0\" checked=\"checked\" name=\"filePrivacy" + uniqueId + "\" id=\"filePrivacy" + uniqueId + "\"/>" + meText + "<br />";
	h += "<input type=\"radio\" value=\"2\" name=\"filePrivacy" + uniqueId + "\" id=\"filePrivacy" + uniqueId + "\"/>" + friendsText + "<br /><br />";


	//Add Allow Comments element.
	h += fileAllowCommentsText + "<br />";
	h += "<input type=\"radio\" value=\"1\" checked=\"checked\" name=\"fileAllowComments" + uniqueId + "\" id=\"fileAllowComments" + uniqueId + "\"/>" + allowText + "<br />";
	h += "<input type=\"radio\" value=\"0\" name=\"fileAllowComments" + uniqueId + "\" id=\"fileAllowComments" + uniqueId + "\"/>" + dontAllowText + "<br /><br />";

	//Add ShowComments element.
	h += fileShowCommentsText + "<br />";
	h += "<input type=\"radio\" value=\"1\" checked=\"checked\" name=\"fileShowComments" + uniqueId + "\" id=\"fileShowComments" + uniqueId + "\"/>" + showText + "<br />";
	h += "<input type=\"radio\" value=\"0\" name=\"fileShowComments" + uniqueId + "\" id=\"fileShowComments" + uniqueId + "\"/>" + hideText + "<br /><br />";


	h += "</td>";
	h += "</tr>";
	h += "</tbody></table>";

	//Create DIV element which will represent the upload list item.
	var div = document.createElement("div");
	div.className = "UploadFile";
	div.innerHTML = h;
	div._guid = guid;
	//_uniqueId is used for fast access to the Title and Description form elements.
	div._uniqueId = uniqueId;

	//Append this upload list item to the custom upload pane.
	document.getElementById("UploadPane").appendChild(div);

	//Increase the ID to guaranty uniqueness.
	uniqueId++;
}

//Synchronize custom upload pane with Image Uploader upload list when 
//some files are added or removed.
function ImageUploader_UploadFileCountChange(){
	if (imageUploader1){
		var uploadFileCount  = imageUploader1.getUploadFileCount();

		//Files are being added.
		if (prevUploadFileCount <= uploadFileCount){
			for (var i = prevUploadFileCount + 1; i <= uploadFileCount; i++){
				addUploadFileHtml(i);
			}
		}
		//Files are being removed.
		else{
			var guidIndexHash = getGuidIndexHash();
			var UploadPane = document.getElementById("UploadPane");
			var i = UploadPane.childNodes.length - 1;
			while (i >= 0){
				if (guidIndexHash["" + UploadPane.childNodes[i]._guid] == undefined){
					UploadPane.removeChild(UploadPane.childNodes[i]);
				}
				i--;
			}
		}

		prevUploadFileCount = uploadFileCount;

		document.getElementById("UploadButton").disabled = (uploadFileCount == 0);
	}
}

//Append the additional data entered by the user (title and description)
//to the upload. If you add more fields, do not forget to modify this event 
//handler to call AddField for these fields.
function ImageUploader_BeforeUpload()
{
	//var guidIndexHash = getGuidIndexHash();
	//var UploadPane = document.getElementById("UploadPane");

    //alert(getSelectedCategories(lstCategories));
    

    
    if(fileTitle.value=='')
    {
        //fileTitle.style.borderColor = "red";
        errMsgFileTitle.style.display = 'block';
        errMsgFileTitle.innerHTML= errMsgFileTitleEmptyText;
        window.location = "#pnlFileInfo";
        return false;
    }
    else if(fileTitle.value.length < 3 || fileTitle.value.length > 50)
    {
        //fileTitle.style.borderColor = "red";
        errMsgFileTitle.style.display = 'block';
        errMsgFileTitle.innerHTML= errMsgFileTitleRangeText;
        window.location = "#pnlFileInfo";
        return false;            
    }
    else
    {
        //fileTitle.style.borderColor = "#CCC";
        errMsgFileTitle.style.display = "none";		    
        imageUploader1.AddField("Title", fileTitle.value);
    }
    
    if(fileDescription.value=='')
    {
        //fileDescription.style.borderColor = "red";
        errMsgFileDescription.style.display = 'block';
        errMsgFileDescription.innerHTML= errMsgFileDescriptionEmptyText;
        window.location = "#pnlFileInfo";
        return false;
    }
    else if(fileDescription.value.length < 3 || fileDescription.value.length > 400)
    {
        //fileDescription.style.borderColor = "red";
        errMsgFileDescription.style.display = 'block';
        errMsgFileDescription.innerHTML= errMsgFileDescriptionRangeText;
        window.location = "#pnlFileInfo";
        return false;            
    }        
    else
    {
        //fileDescription.style.borderColor = "#CCC";
        errMsgFileDescription.style.display = "none";
        //imageUploader1.setUploadFileDescription(index, fileDescription.value);
        imageUploader1.AddField("Desc", fileDescription.value);
    }


    if(lstCategories.value==0)
    {
        errMsgListCategory.style.display= "block";
        window.location = "#pnlFileInfo";
        return false;
    }
    else
    {
        imageUploader1.AddField("Categories", getSelectedCategories(lstCategories,'value'));
        imageUploader1.AddField("CategoriesText", getSelectedCategories(lstCategories,'text'));
        errMsgListCategory.style.display= "none";
    }
    
    imageUploader1.AddField("tags", document.getElementById(lblFileTags).value)
    
//	for (var i = 0; i < UploadPane.childNodes.length; i++)
//	{
//        var div = UploadPane.childNodes[i];

//        var index = guidIndexHash[div._guid];

//        var fileTitle = document.getElementById("fileTitle" + div._uniqueId);
//        var fileDescription = document.getElementById("fileDescription" + div._uniqueId);
//        var fileTags = document.getElementById("fileTags" + div._uniqueId);
//        var filePrivacy = getRadioValue("filePrivacy" + div._uniqueId);
//        var fileAllowComments = getRadioValue("fileAllowComments" + div._uniqueId);
//        var fileShowComments = getRadioValue("fileShowComments" + div._uniqueId);
//        var errMsgFileTitle = document.getElementById("errMsgFileTitle" + div._uniqueId);
//        var errMsgFileDescription = document.getElementById("errMsgFileDescription" + div._uniqueId);
//		
//        if(fileTitle.value=='')
//        {
//            fileTitle.style.borderColor = "red";
//            errMsgFileTitle.style.display = 'block';
//            errMsgFileTitle.innerHTML= errMsgFileTitleEmptyText;
//            window.location = '#' + document.getElementById('UploadPane').getElementsByTagName('input').item(i).id;
//            return false;
//        }
//        else if(fileTitle.value.length < 3 || fileTitle.value.length > 50)
//        {
//            fileTitle.style.borderColor = "red";
//            errMsgFileTitle.style.display = 'block';
//            errMsgFileTitle.innerHTML= errMsgFileTitleRangeText;
//            window.location = '#' + document.getElementById('UploadPane').getElementsByTagName('input').item(i).id;
//            return false;            
//        }
//        else
//        {
//            fileTitle.style.borderColor = "#CCC";
//            errMsgFileTitle.style.display = "none";		    
//            imageUploader1.AddField("Title_" + index, fileTitle.value);
//        }
//        
//        if(fileDescription.value=='')
//        {
//            fileDescription.style.borderColor = "red";
//            errMsgFileDescription.style.display = 'block';
//            errMsgFileDescription.innerHTML= errMsgFileDescriptionEmptyText;
//            window.location = '#' + document.getElementById('UploadPane').getElementsByTagName('textarea').item(i).id;
//            return false;
//        }
//        else if(fileDescription.value.length < 3 || fileDescription.value.length > 400)
//        {
//            fileDescription.style.borderColor = "red";
//            errMsgFileDescription.style.display = 'block';
//            errMsgFileDescription.innerHTML= errMsgFileDescriptionRangeText;
//            window.location = '#' + document.getElementById('UploadPane').getElementsByTagName('input').item(i).id;
//            return false;            
//        }        
//        else
//        {
//            fileDescription.style.borderColor = "#CCC";
//            errMsgFileDescription.style.display = "none";
//            imageUploader1.setUploadFileDescription(index, fileDescription.value);
//        }
//         
//         imageUploader1.AddField("Tags_" + index, fileTags.value);
//         imageUploader1.AddField("Privacy_" + index, filePrivacy);
//         imageUploader1.AddField("AllowComments_" + index, fileAllowComments);
//         imageUploader1.AddField("ShowComments_" + index, fileShowComments);
//    }
}

//This function is used to handle Remove link click. It removes an item 
//from the custom upload pane by specified GUID.
function Remove_click(guid){
	var guidIndexHash = getGuidIndexHash();
	imageUploader1.UploadFileRemove(guidIndexHash[guid]);
}

//This function posts data on server.
function UploadButton_click(){
	imageUploader1.Send();
}

   
  function getRadioValue(elementName)   
  {
      var element = document.getElementsByName(elementName);
      var bt_count = element.length; // can't use element.length in the loop, as it would decrement

      for (var i = 0; i <bt_count; i++)   
          if (element[i].checked == true)  
              return element[i].value;

  }

function getSelectedCategories(multiList, returnedValue)   
{
    var Categories = "";
    
    for (var i = 0; i < multiList.options.length; i++) 
    {
        if (multiList.options[i].selected) 
        {
            if(returnedValue == 'value') Categories += multiList.options[i].value + ",";
            else Categories += multiList.options[i].text + ",";
            
        }
    }
    
    return Categories;
}

//iuembed.js
// Aurigma Image Uploader Dual 5.x Embedding Script 
// Version 2.0.4.0 Feb 20, 2008
// Copyright(c) Aurigma Inc. 2002-2008

function __Browser(){
	var a=navigator.userAgent.toLowerCase();
	this.isOpera=(a.indexOf("opera")!=-1);
	this.isKonq=(a.indexOf('konqueror')!=-1);
	this.isSafari=(a.indexOf('safari')!=-1)&&(a.indexOf('mac')!=-1);
	this.isKhtml=this.isSafari||this.isKonq;
	this.isIE=(a.indexOf("msie")!=-1)&&!this.isOpera;
	this.isWinIE=this.isIE;
	this.isCSS1Compat=(!this.isIE)||(document.compatMode&&document.compatMode=="CSS1Compat");
}

var __browser=new __Browser();

//Create set/get expando methods for ActiveX
function _createExpandoMethods(id){
	var o=document.getElementById(id);
	var props=new Array();
	var hasPaneItemApiElements=false;
	for (propName in o){
		var c=propName.charAt(0);
		if (c==c.toUpperCase()){
			props.push(propName);
			if (propName=="PaneItemDesign"){
				hasPaneItemApiElements=true;
			}
		}
	}
	for (i=0;i<props.length;i++){
		//Check whether property is indexed
		if (typeof(o[props[i]])=="unknown"){
			eval("o.set"+props[i]+"=function(i,v){this."+props[i]+"(i)=v;};");
			eval("o.get"+props[i]+"=function(i){return this."+props[i]+"(i);};");
		}
		else{
			eval("o.set"+props[i]+"=function(v){this."+props[i]+"=v};");
			eval("o.get"+props[i]+"=function(){return this."+props[i]+"};");
		}
	}
	if (hasPaneItemApiElements){
		eval("o.setPaneItemDesign = function(Pane, Index, Value){this.PaneItemDesign(Pane, Index) = Value;};");
		eval("o.getPaneItemDesign = function(Pane, Index){return this.PaneItemDesign(Pane, Index);};");		
		//eval("o.getPaneItemCount = function(Pane){return this.PaneItemCount(Pane);};");
		//eval("o.getPaneItemChecked = function(Index){return this.PaneItemChecked(Index);};");
		//eval("o.getPaneItemCanBeUploaded = function(Index){return this.PaneItemCanBeUploaded(Index);};");
		eval("o.getPaneItemSelected = function(Pane, Index){return this.PaneItemSelected(Pane, Index);};");
		eval("o.setPaneItemEnabled = function(Pane, Index, Value){this.PaneItemEnabled(Pane, Index) = Value;};");
		eval("o.getPaneItemEnabled = function(Pane, Index){return this.PaneItemEnabled(Pane, Index);};");
	}
}

//Installation instructions
function _addInstructions(obj){
	obj.instructionsEnabled=true;
	if (obj.controlClass=="FileDownloader"){
		obj.instructionsCommon="<p>File Downloader ActiveX control is necessary to download "+
			"files quickly and easily. You will be able to select required files "+
			"in a user-friendly interface and simply click a <strong>Download</strong> button. "+
			"Installation will take up to few minutes, please be patient. To install File Downloader, ";
		obj.instructionsNotWinXPSP2="please reload the page and click the <strong>Yes</strong> button " +
			"when you see the control installation dialog.";
		obj.instructionsWinXPSP2="please click the <strong>Information Bar</strong>. After page reload click <strong>Install</strong> when "+
			"you see the control installation dialog.";
		obj.instructionsVista = "please click on the <strong>Information Bar</strong> and select <strong>Install ActiveX Control</strong> "+
			"from the dropdown menu. After page reload click <strong>Continue</strong> and then <strong>Install</strong> when "+
			"you see the control installation dialog.";
		obj.instructionsCommon2="</p><p><strong>NOTE:</strong> If control fails to be installed, it may mean that it has been inserted to the page incorrectly. "+
			"Refer File Downloader documentation for more details.</p>";
	} else {
		obj.instructionsCommon="<p>Image Uploader ActiveX control is necessary to upload "+
			"your files quickly and easily. You will be able to select multiple images "+
			"in user-friendly interface instead of clumsy input fields with <strong>Browse</strong> button. "+
			"Installation will take up to few minutes, please be patient. To install Image Uploader, ";
		obj.instructionsNotWinXPSP2="please reload the page and click the <strong>Yes</strong> button " +
			"when you see the control installation dialog.";
		obj.instructionsWinXPSP2="please click on the <strong>Information Bar</strong> and select " +
			"<strong>Install ActiveX Control</strong> from the dropdown menu. After page reload click <strong>Install</strong> when "+
			"you see the control installation dialog.";
		obj.instructionsVista = "please click on the <strong>Information Bar</strong> and select <strong>Install ActiveX Control</strong> "+
			"from the dropdown menu. After page reload click <strong>Continue</strong> and then <strong>Install</strong> when "+
			"you see the control installation dialog.";
		obj.instructionsCommon2="</p>";
	}
}

function ControlWriter(id,width,height){
	//Private
	this._params=new Array();
	this._events=new Array();
	
	_addInstructions(this);

	this._getObjectParamHtml=function(name,value){
		return "<param name=\""+name+"\" value=\""+value+"\" />";
	}

	this._getObjectParamsHtml=function(){
		var r="";
		var p=this._params;
		var i;
		for (i=0;i<p.length;i++){
			r+=this._getObjectParamHtml(p[i].name,p[i].value);
		}
		return r;
	}

	this._getObjectEventsHtml=function(){
		var r="";
		var e=this._events;
		for (i=0;i<e.length;i++){
			r+=this._getObjectParamHtml(e[i].name+"Listener",e[i].listener);
		}
		return r;
	}

	this._getEmbedParamHtml=function(name,value){
		return " "+name+"=\""+value+"\"";	
	}

	this._getEmbedParamsHtml=function(){
		var r="";
		var p=this._params;
		var i;
		for (i=0;i<p.length;i++){
			r+=this._getEmbedParamHtml(p[i].name,p[i].value);
		}
		return r;
	}

	this._getEmbedEventsHtml=function(){
		var r="";
		var e=this._events;
		for (i=0;i<e.length;i++){
			r+=this._getEmbedParamHtml(e[i].name+"Listener",e[i].listener);
		}
		return r;
	}

	//Public

	//Properties
	this.id=id;
	this.width=width;
	this.height=height;

	this.activeXControlEnabled=true;
	this.activeXControlVersion="";

	this.javaAppletEnabled=true;
	this.javaAppletCodeBase="./";
	this.javaAppletCached=true;
	this.javaAppletVersion="";

	this.fullPageLoadListenerName=null;

	//Methods
	this.addParam=function(paramName,paramValue){
		var p=new Object();
		p.name=paramName;
		p.value=paramValue;
		this._params.push(p);
	}

	this.addEventListener=function(eventName,eventListener){
		try
	        {
        	    	eval("var checkListener = " + eventListener + ";");
	            	if (checkListener == null)
			{
				return;
        		}
	        }
        	catch (e)
	        {
        	    	return;
	        }
		var p=new Object();
		p.name=eventName;
		p.listener=eventListener;
		this._events.push(p);
	}

	this.getActiveXInstalled=function(){
		if (this.activeXProgId){
			try{
				var a=new ActiveXObject(this.activeXProgId);
				return true;
			}
			catch(e){
				return false;
			}
		}
		return false;
	}

	this.getHtml=function(){
		var r="";
		if (this.fullPageLoadListenerName){
			r+="<" + "script type=\"text/javascript\">";
			r+="var __"+this.id+"_pageLoaded=false;";
			r+="var __"+this.id+"_controlLoaded=false;";
			r+="function __fire_"+this.id+"_fullPageLoad(){";
			r+="if (__"+this.id+"_pageLoaded&&__"+this.id+"_controlLoaded){";
			r+=this.fullPageLoadListenerName + "();";
			r+="}";
			r+="}";
			var pageLoadCode="new Function(\"__"+this.id+"_pageLoaded=true;__fire_"+this.id+"_fullPageLoad();\")";
			if (__browser.isWinIE){
				r+="window.attachEvent(\"onload\","+pageLoadCode+");";
			}
			else{
				r+="var r=window.addEventListener?window:document.addEventListener?document:null;";
				r+="if (r){r.addEventListener(\"load\","+pageLoadCode+",false);}";
			}
			r+="<"+"/script>";
		}		

		//ActiveX control
		if(__browser.isWinIE&&this.activeXControlEnabled){
			var v=this.activeXControlVersion.replace(/\./g,",")
			var cb=this.activeXControlCodeBase+(v==""?"":"#version="+v);

			r+="<" + "script for=\""+this.id+"\" event=\"InitComplete()\">";
			r+="_createExpandoMethods(\""+this.id+"\");";
			if (this.fullPageLoadListenerName){
				r+="__"+this.id+"_controlLoaded=true;";
				r+="__fire_"+this.id+"_fullPageLoad();";
			}
			r+="<"+"/script>";

			r+="<object id=\""+this.id+"\" name=\""+this.id+"\" classid=\"clsid:"+this.activeXClassId+"\" codebase=\""+cb+"\" width=\""+this.width+"\" height=\""+this.height+"\">";
			if (this.instructionsEnabled){
				r+=this.instructionsCommon;
				var isXPSP2 = (window.navigator.userAgent.indexOf("SV1") != -1) || (window.navigator.userAgent.indexOf("MSIE 7.0") != -1);
				var isVista = (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1) && (window.navigator.userAgent.indexOf("MSIE 7.0") != -1);
				if (isVista) {
					r+=this.instructionsVista;
					//r+=this.instructionsWinXPSP2;
				} else if (isXPSP2) {
					r+=this.instructionsWinXPSP2;
				}
				else{
					r+=this.instructionsNotWinXPSP2;
				}
				r+=this.instructionsCommon2;
			}
			r+=this._getObjectParamsHtml();
			r+="</object>";

			//Event handlers
			var e=this._events;
			var eventParams;
			for (i=0;i<e.length;i++){
				if (this.controlClass=="FileDownloader"){
					switch (e[i].name){
						case "DownloadComplete":
							eventParams="Value";
							break;
						case "DownloadItemComplete":
							eventParams="Result, ErrorPage, Url, FileName, ContentType, FileSize";
							break;
						case "DownloadStep":
							eventParams="Step";
							break;
						case "Progress":
							eventParams="PercentTotal, PercentCurrent, Index";
							break;
						case "Error":
							eventParams="ErrorCode, HttpErrorCode, ErrorPage, Url, Index";
							break;
						default:
							eventParams="";
					}
					r+="<script for=\""+this.id+"\" event=\""+e[i].name+"("+eventParams+")\">";
					r+=e[i].listener+"("+eventParams+");";
					r+="<"+"/script>";
				}
				else {
					switch (e[i].name){
						case "Progress":
							eventParams="Status, Progress, ValueMax, Value, StatusText";
							break;
						case "InnerComplete":
							eventParams="Status, StatusText";
							break;
						case "AfterUpload":
							eventParams="htmlPage";
							break;
						case "ViewChange":
						case "SortModeChange":
							eventParams="Pane";
							break;
						case "Error":
							eventParams="ErrorCode, HttpResponseCode, ErrorPage, AdditionalInfo";
							break;
						case "PackageBeforeUpload":
							eventParams = "PackageIndex";
						    	break;
						case "PackageError":
						    	eventParams = "PackageIndex, ErrorCode, HttpResponseCode, ErrorPage, AdditionalInfo";
						    	break;
						case "PackageComplete":
						    	eventParams = "PackageIndex, ResponsePage";
						    	break;
						case "PackageProgress":
						    	eventParams = "PackageIndex, Status, Progress, ValueMax, Value, StatusText";
						    	break;
						default:
							eventParams="";
					}
				}
				r+="<" + "script for=\""+this.id+"\" event=\""+e[i].name+"("+eventParams+")\">";
				if (e[i].name=="BeforeUpload" || e[i].name=="PackageComplete"){
					r+="return ";
				}
				r+=e[i].listener+"("+eventParams+");";
				r+="<"+"/script>";
			}

		}
		else 
		//Java appplet
		if(this.javaAppletEnabled){
			if (this.fullPageLoadListenerName){
				r+="<" + "script type=\"text/javascript\">";
				r+="function __"+this.id+"_InitComplete(){";
				r+="__"+this.id+"_controlLoaded=true;";
				r+="__fire_"+this.id+"_fullPageLoad();";
				r+="}";
				r+="<"+"/script>";
			}

			//<object> for IE and <applet> for Safari
			if (__browser.isWinIE||__browser.isKhtml){
				if (__browser.isWinIE){
					r+="<object id=\""+this.id+"\" classid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\" codebase=\""+window.location.protocol+"//java.sun.com/update/1.4.2/jinstall-1_4-windows-i586.cab#Version=1,4,0,0\" width=\""+this.width+"\" height=\""+this.height+"\">";
				}
				else{
					r+="<applet id=\""+this.id+"\" code=\""+this.javaAppletClassName+"\" java_codebase=\"../\" align=\"baseline\" archive=\""+this.javaAppletJarFileName+"\" mayscript=\"true\" scriptable=\"true\" width=\""+this.width+"\" height=\""+this.height+"\">";
				}

				if (this.javaAppletCached&&this.javaAppletVersion!=""){
					r+=this._getObjectParamHtml("cache_archive",this.javaAppletJarFileName);
					var v=this.javaAppletVersion.replace(/\,/g,".");
					//r+=this._getObjectParamHtml("cache_version",v+","+v);
					r+=this._getObjectParamHtml("cache_version",v);
				}

				r+=this._getObjectParamHtml("id",this.id);
				r+=this._getObjectParamHtml("type","application/x-java-applet;version=1.4");
				r+=this._getObjectParamHtml("codebase",this.javaAppletCodeBase);
				r+=this._getObjectParamHtml("archive",this.javaAppletJarFileName);
				r+=this._getObjectParamHtml("code",this.javaAppletClassName);
				r+=this._getObjectParamHtml("scriptable","true");
				r+=this._getObjectParamHtml("mayscript","true");

				r+=this._getObjectParamsHtml();

				r+=this._getObjectEventsHtml();

				if (this.fullPageLoadListenerName){
					r+=this._getObjectParamHtml("InitCompleteListener","__"+this.id+"_InitComplete");
				}
				if (__browser.isWinIE){
					r+="</object>";
				}
				else{
					r+="</applet>";
				}
			}
			//<embed> for all other browsers
			else{
				r+="<embed id=\""+this.id+"\" type=\"application/x-java-applet;version=1.4\" codebase=\""+this.javaAppletCodeBase+"\" code=\""+this.javaAppletClassName+"\" archive=\""+this.javaAppletJarFileName+"\" width=\""+this.width+"\" height=\""+this.height+"\" scriptable=\"true\" mayscript=\"true\" pluginspage=\""+window.location.protocol+"//java.sun.com/products/plugin/index.html#download\"";

				if (this.javaAppletCached&&this.javaAppletVersion!=""){
					r+=this._getEmbedParamHtml("cache_archive",this.javaAppletJarFileName);
					var v=this.javaAppletVersion.replace(/\,/g,".");
					//r+=this._getEmbedParamHtml("cache_version",v+","+v);
					r+=this._getEmbedParamHtml("cache_version",v);
				}

				r+=this._getEmbedParamsHtml();

				r+=this._getEmbedEventsHtml();

				if (this.fullPageLoadListenerName){
					r+=this._getEmbedParamHtml("InitCompleteListener","__"+this.id+"_InitComplete");
				}
				r+=">";
				r+="</embed>";
			}
		}
		else
		{
			r+="Your browser is not supported.";
		}
		
		//For backward compatibility
		this.controlType=this.getControlType();
			
		return r;
	}

	this.getControlType=function(){
		return (__browser.isWinIE&&this.activeXControlEnabled)?"ActiveX":(this.javaAppletEnabled?"Java":"None");
	}
	
	this.writeHtml=function(){
		document.write(this.getHtml());
	}
}

function ImageUploaderWriter(id,width,height){
	this._base=ControlWriter;
	this._base(id,width,height);
	//These properties should be modified for private-label versions only
	this.activeXControlCodeBase="ImageUploader5.cab";
	this.activeXClassId="5D637FAD-E202-48D1-8F18-5B9C459BD1E3";
	this.activeXProgId="Aurigma.ImageUploaderEx.5";
	this.javaAppletJarFileName="ImageUploader5.jar";
	this.javaAppletClassName="com.aurigma.imageuploader.ImageUploader.class";

	//Extend
	this.showNonemptyResponse="off";
	this._getHtml=this.getHtml;
	this.getHtml=function(){
		var r="";
		if (this.showNonemptyResponse!="off"){
			r+="<" + "script type=\"text/javascript\">";
			r+="function __"+this.id+"_InnerComplete(Status,StatusText){";
			r+="if (new String(Status)==\"COMPLETE\" && new String(StatusText).replace(/\\s*/g,\"\")!=\"\"){";
			if (this.showNonemptyResponse=="dump"){
				r+="var f=document.createElement(\"fieldset\");";
				r+="var l=f.appendChild(document.createElement(\"legend\"));";
				r+="l.appendChild(document.createTextNode(\"Server Response\"));";
				r+="var d=f.appendChild(document.createElement(\"div\"));";
				r+="d.innerHTML=StatusText;";
				r+="var b=f.appendChild(document.createElement(\"button\"));";
				r+="b.appendChild(document.createTextNode(\"Clear Server Response\"));";
				r+="b.onclick=function(){var f=this.parentNode;f.parentNode.removeChild(f)};";
				r+="document.body.appendChild(f);";
			}
			else{
				var s="";
				for (var i=0;i<80;i++){s+="-";}
				r+="alert(\""+s+"\\r\\nServer Response\\r\\n"+s+"\\r\\n\"+StatusText);";
			}
			r+="}";
			r+="}";
			r+="<"+"/script>";
			this.addEventListener("InnerComplete","__"+this.id+"_InnerComplete");
		}
		return r+this._getHtml();
	}
}

function ThumbnailWriter(id,width,height){
	this._base=ControlWriter;
	this._base(id,width,height);
	//These properties should be modified for private label versions only
	this.activeXControlCodeBase="ImageUploader5.cab";
	this.activeXClassId="83AC1413-FCE4-4A46-9DD5-4F31F306E71F";
	this.activeXProgId="Aurigma.ThumbnailEx.5";
	this.javaAppletJarFileName="ImageUploader5.jar";
	this.javaAppletClassName="com.aurigma.imageuploader.Thumbnail.class";
}

function ShellComboBoxWriter(id,width,height){
	this._base=ControlWriter;
	this._base(id,width,height);
	//These properties should be modified for private label versions only
	this.activeXControlCodeBase="ImageUploader5.cab";
	this.activeXClassId="3BF72F68-72D8-461D-A884-329D936C5581";
	this.activeXProgId="Aurigma.ShellComboEx.5";
	this.javaAppletJarFileName="ImageUploader5.jar";
	this.javaAppletClassName="com.aurigma.imageuploader.ShellComboBox.class";
}

function UploadPaneWriter(id,width,height){
	this._base=ControlWriter;
	this._base(id,width,height);
	//These properties should be modified for private label versions only
	this.activeXControlCodeBase="ImageUploader5.cab";
	this.activeXClassId="78E9D883-93CD-4072-BEF3-38EE581E2839";
	this.activeXProgId="Aurigma.UploadPaneEx.5";
	this.javaAppletJarFileName="ImageUploader5.jar";
	this.javaAppletClassName="com.aurigma.imageuploader.UploadPane.class";
}

function FileDownloaderWriter(id,width,height){
	this._base=ControlWriter;
	this._base(id,width,height);
	//These properties should be modified for private label versions only
	this.activeXControlCodeBase="FileDownloader2.cab";
	this.activeXClassId="AAB58191-AFBE-4366-93FD-1E45F7C97FA0";
	this.activeXProgId="Aurigma.FileDownloader.2";
	this.javaAppletEnabled=false;
	this.controlClass="FileDownloader";
}

function getControlObject(id){
	if (__browser.isSafari){
		return document[id];
	}
	else{
		return document.getElementById(id);
	}
}

function getImageUploader(id){
	return getControlObject(id);
}

function getFileDownloader(id){
	return getControlObject(id);
}

//js.js

function SelectNewest(BcFileType)
{
    SwitchTabs('Newest_tab:on','Popular_tab:off', 'MostViewed_tab:off');
    DisplayLayers('NewestVideos:on','PopularVideos:off', 'MostViewedVideos:off'); 
    LoadAjaxInBox('NewestVideos', AjaxVideosURL , 'POST', 'action=newest&bctype=' + BcFileType, 'Loading...', false);
}
function SelectPopular(BcFileType)
{
    SwitchTabs('Newest_tab:off','Popular_tab:on', 'MostViewed_tab:off');
    DisplayLayers('NewestVideos:off','PopularVideos:on', 'MostViewedVideos:off'); 
    LoadAjaxInBox('PopularVideos', AjaxVideosURL , 'POST', 'action=popular&bctype=' + BcFileType, 'Loading...', false);
}
function SelectFeatured(BcFileType)
{
    SwitchTabs('Newest_tab:off','Popular_tab:off', 'MostViewed_tab:off');
    DisplayLayers('NewestVideos:off','PopularVideos:off', 'MostViewedVideos:off'); 
    LoadAjaxInBox('FeaturedVideos', AjaxVideosURL , 'POST', 'action=featured&bctype=' + BcFileType, 'Loading...', false);
}
function SelectMostViewed(BcFileType)
{
    SwitchTabs('Newest_tab:off','Popular_tab:off', 'MostViewed_tab:on');
    DisplayLayers('NewestVideos:off','PopularVideos:off', 'MostViewedVideos:on'); 
    LoadAjaxInBox('MostViewedVideos', AjaxVideosURL , 'POST', 'action=viewed&bctype=' + BcFileType, 'Loading...', false);
}

function SwitchTabs()
{
    var Argument;
    var KeyValue
    // iterate through non-separator arguments
    for (var i = 0; i < arguments.length; i++)
    {
        Argument = arguments[i].split(':');
        
        switch(Argument[1])
        {
            case "on":
                j$Obj(Argument[0]).className = "BriefcaseSelected";
                break;
                
            case "off":
                j$Obj(Argument[0]).className = "BriefcaseNotSelected";
                break;
            default:
                j$Obj(Argument[0]).className = "BriefcaseNotSelected";
                break;
        }        
    }
}

function DisplayLayers()
{
    var Argument;
    var KeyValue
    
    // iterate through non-separator arguments
    for (var i = 0; i < arguments.length; i++)
    {
        Argument = arguments[i].split(':');
        
        switch(Argument[1])
        {
            case "on":
                j$Obj(Argument[0]).style.display = "block";
                break;
                
            case "off":
                j$Obj(Argument[0]).style.display = "none";
                break;
                
            default:
                j$Obj(Argument[0]).style.display = "none";
                break;
        }        
    }
}


function SelectAjaxTab(SelectedTab, TotalTabs, AjaxAction, BcFileType)
{
    for (var i = 1; i < TotalTabs + 1; i++)
    {
        j$Obj("Tab" + i).className = "BriefcaseNotSelected";
    }
    
    j$Obj("Tab" + SelectedTab).className = "BriefcaseSelected";
    
    for (var i = 1; i < TotalTabs + 1; i++)
    {
        j$Obj("Tab" + i + "Content").style.display = "none";
    }
    
    j$Obj("Tab" + SelectedTab + "Content").style.display = "block";
    
    LoadAjaxInBox('Tab' + SelectedTab + 'Content', AjaxVideosURL, 'POST', 'action=' + AjaxAction + '&country=' + UserCountry + '&fileid=' + FileID + '&bctype=' + BcFileType, 'Loading...', false);
}


function ExecuteSearch()
{
        // GET TAG VALUE - OmarAA
        var elValue= document.getElementById('formSerachTextInc').value;
        
        var validated = true;
        var errValue = "";

        // CHECK IF TAG IS EMPTY OR NULL - OmarAA
        if(elValue == null || elValue == "") {
               validated = false;
               errValue += document.getElementById('vldSearchTextIncRequired').value;
        }
        
        // STRIP HTML AND JS TAGS - OMAR B
        var re= /<\S[^><]*>/g;
        for (i=0; i<elValue.length; i++)
        {
            elValue=elValue.replace(re,"");
        }

        if (validated == true) {
            // VALIDATE Tag - OmarAA
            var regexValue= document.getElementById('RegExvldTagIncText').value;        
            var re = new RegExp(regexValue);         
            if(!elValue.match(re))
            {
                   //validated = false;
                   //errValue += document.getElementById('vldSearchIncText').value;
            }
        }
        
        // IF VALIDATED ADD THE TAG USING AJAX, IF NOT THEN SHOW ERROR MESSAGE - OmarAA
        if(validated == true) {
            
            // do the redirect here
            window.location = replace(SearchURL, "||TAG||", elValue);
            
        } else {
           //document.getElementById('errformSearchTextInc').innerHTML = errValue;
        }
} 

// KEY PRESS ON A TEXTBOX DOES NOT SUBMIT THE PAGE - OMAR AA
function KeyPress(e, field)
{
    var oEvent = window.event ? window.event : e;

    var isDOM = (document.getElementById ? true : false);
    var isNS4 = (document.layers ? true : false);

    if (document.all != 'undefined') key = oEvent.keyCode;
    else if (isDOM) key = oEvent.charCode;
    else if (isNS4) key = oEvent.which;

    if (key == 13)
    {
        ExecuteSearch();
        oEvent.cancelBubble = true;
        return false;
    }
    else
    { return true; }
}

// This takes two drop/options lists and moves one option from the source to the target list.
// You can provide either the item text or the index. The index takes priority if it were privided.
// - Laith
function MoveListItem(SourceListID, TargetListID, ItemText, ItemIndex)
{
    var SourceList = j$Obj(SourceListID);
    var TargetList = j$Obj(TargetListID);
    
    var SourceListItem = GetListItem(SourceListID, ItemText, ItemIndex);    
    
    //try {                
    //    TargetList.add(SourceListItem, null); // standards compliant; doesn't work in IE
    //}
    //catch(ex)
    //{
    //    TargetList.add(SourceListItem, 0); // IE only
    //}

	// THE UPPER CODE IS NOT WORKING ON IE, SO WE CHANGED THE MOVE FUNCTION TO THE FOLLOWING - OMAR B
	OptionValue = SourceList.item(SourceList.selectedIndex).value;
	OptionText = SourceList.item(SourceList.selectedIndex).text;        
    TargetList.options[TargetList.length] = new Option(OptionText, OptionValue, false, false);
    SourceList.options[SourceList.selectedIndex] = null;

    // remove the item from the source list
    //FriendsList.remove(SourceListItem);
}

// This returns the options list item.
// you can either give it the item text or the index.
// The index takes priority if it were provided.
// - Laith
function GetListItem(ListID, ItemText, ItemIndex) {
    var List = j$Obj(ListID);
    if (ItemText == "" || ItemText == null || ItemIndex > -1) {
        return List.options[ItemIndex];
    }
    else {
        for(var i=0; i < List.length; i++)
        {
            if(List.options[i].text == ItemText)
            {
                return List.options[i];
            }
        }
    }
}

function SelectFirstListItem(ListID) {
    var List = j$Obj(ListID);
    if (List.length > -1)
    {
        List.selectedIndex = 0;
    }    
}

// This will copy/move page elements between the source and target divs
// to move, set KeepOriginal = false, otherwise KeepOriginal = true
// - Laith
// This was moved to jJsFw.js by FM 24-12-2007


/* Not Used */
function ChildToTop(ParentID, ChildID)
{
    var Parent = j$Obj(ParentID);
    var Child = j$Obj(ChildID);
    
    var Children = Parent.childNodes;
    
    // loop through children in reverse
    for (var i = Children.length-1; i >= 0; i--)
    { 
        var c = Parent.removeChild(Children[i]);
         
        if (c.id == ChildID)
        {
            // skip, dont add it
            Child = c; 
        }
        else
        {
           Parent.appendChild(c);   
        }
    }
    Parent.appendChild(Child);  
}

//OwnerFile.js
function funcCancelbtn() {
    HideDiv('SendFile');
    HideDiv('ShareFile');
    HideDiv('FileSettings');
    HideDiv('ReportAbuse');    
    
    try {
      j$Obj('SendTab').style.backgroundColor = "#ffffff"; 
    }
    catch (err)
    {}
    try {
      j$Obj('ShareTab').style.backgroundColor = "#ffffff";
    }
    catch (err)
    {}
    try {
      j$Obj('SettingsTab').style.backgroundColor = "#ffffff";
    }
    catch (err)
    {}
    try {
     j$Obj('AbuseTab').style.backgroundColor = "#ffffff";  
    }
    catch (err)
    {}
}


function ShowTaskBar(Task, TaskTab) {
    ShowDiv(Task);
    j$Obj(TaskTab).style.backgroundColor = "#eee";
}


function LoadTaskBar(FileID, LayerID, Action, BcFileType) {
    LoadAjaxInBox(LayerID, AjaxTaskBarUrl, 'POST', 'action=' + Action + '&fileid=' + FileID + "&bctype=" + BcFileType, 'Loading...', true);    
}


function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 

    //determine the direction for the blending, if start and end are the same nothing happens 
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
    } 
    else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) 
            { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++;
        } 
    } 
} 


//change the opacity for different browsers 
function changeOpac(opacity, id) { 
    var object = j$Obj(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
}


function funcEditFileTitle() {
    HideDiv('spanFileTitle');
    ShowDiv('spanEditFileTitle');
    j$Obj('formFileTitle').value = j$Obj('lblFileTitleEditable').innerHTML;
}


function funcEditFileDescription() {
    HideDiv('spanFileDescription');
    ShowDiv('spanEditFileDescription');
    j$Obj('formFileDescription').value = j$Obj('lblFileDescription').innerHTML;
}


function funcSaveFileTitle() {
    var NewTitle;
    var formFileTitle;
    var ValidTitle;
    
    formFileTitle = j$Obj("formFileTitle");
    NewTitle = formFileTitle.value;             
    
    NewTitle = stripHTMLTags(NewTitle);
    formFileTitle.value = NewTitle;     
    
    ValidTitle = ValidateForm(NewTitle,'errformFileTitle','RegExvldFileTitle', new Array("3", "50"),'vldFileTitleErrRequired','vldFileTitleErr','vldFileTitleErrRange');
    
    if (ValidTitle) {
        formFileTitle.value = "Updating...";  
        funcSetFileTD(NewTitle, j$Obj("lblFileDescription").innerHTML, 'title')
    }
}


function funcSaveFileDescription() {
    var NewDescr;
    var formFileDescription;
    var ValidDescription;
    
    formFileDescription = j$Obj("formFileDescription");
    
    var NewDescr = formFileDescription.value;
    
    //Strip HTML tags
    NewDescr = stripHTMLTags(NewDescr);
    formFileDescription.value = NewDescr;  
    
    ValidDescription = ValidateForm(NewDescr,'errformFileDescr','RegExvldFileDescr',new Array("3", "400"),'vldFileDescrErrRequired','vldFileDescrErr','vldFileDescrErrRange');

    if (ValidDescription) {
        formFileDescription.value = "Updating..."; 
        funcSetFileTD(j$Obj("lblFileTitleEditable").innerHTML, NewDescr, 'Description')
        // sow the no description message if the descript is left empty
    }
}


function funcCancelFileTitle() {
    ShowDiv('spanFileTitle');
    HideDiv('spanEditFileTitle');
    j$Obj("errformFileTitle").innerHTML = "";
}


function funcCancelFileDescription() {

    ShowDiv('spanFileDescription');
    HideDiv('spanEditFileDescription');
    j$Obj("errformFileDescr").innerHTML = "";
}

// THE FUNCTION BREAK THE LONG WORDD _ OMAR B
function FuncBreakWord(text, breakPoint) {  
  return text.replace(RegExp("(\\w{" + breakPoint + "})(\\w)", "g"), function(all,text,char){ 
    return text + "<wbr>" + char; 
  }); 
}

// THE FUNCTION THAT SETS THE FILE SETTINGS
function funcSetFileTD(FileTitle, FileDescription, ChangedField)
{
    var formFileTitle = j$Obj("formFileTitle");
    var formFileDescription = j$Obj("formFileDescription");
    
    var SetFileTDAJAX = new JeeranRemoteScripting();
	SetFileTDAJAX.SetRequestMethod("POST");
	SetFileTDAJAX.SetRequestURL(AjaxFileTDUrl);
	SetFileTDAJAX.SetData("fileid=" + FileID + "&title=" + FileTitle + "&desc=" + FileDescription + "&changedValue=" + ChangedField + "&bctype=" + BcType);
	SetFileTDAJAX.SetRequestAsynch(true);
    SetFileTDAJAX.InitializeRequester();
        //ShowDiv('tabLoadingSetFileTitle');
        //ShowDiv('tabLoadingSetFileDescription');
	SetFileTDAJAX.SendRequest();
	//waiting?
	
    formFileTitle.disabled = true;
    formFileDescription.disabled = true;
    
	SetFileTDAJAX.OnLoaded = function() {
	    var result = SetFileTDAJAX.GetText();
        if(result != "" && result != null)
        {
            formFileTitle.value=j$Obj("lblFileTitleEditable").innerHTML;
            j$Obj("errformFileTitle").innerHTML=result;
            j$Obj("errformFileTitle").display='block';
        }
        else
        {

           funcCancelFileTitle();
            funcCancelFileDescription();
            j$Obj("lblFileTitleEditable").innerHTML = FileTitle; 
         
        }
        
        j$Obj("lblFileDescription").innerHTML = FuncBreakWord(FileDescription,15);

        //HideDiv('tabLoadingSetFileTitle');
        //HideDiv('tabLoadingSetFileDescription');
	    SetFileTDAJAX = null;
	    
	    formFileTitle.disabled = false;
        formFileDescription.disabled = false;
    
	}
	
	SetFileTDAJAX.OnFailure = function() {
	    //HideDiv('tabLoadingSetFileTitle');
	    //HideDiv('tabLoadingSetFileDescription');
        SetFileTDAJAX = null; 
        formFileTitle.disabled = false;
        formFileDescription.disabled = false;  
	}
}


// FUNCTION THAT CALLS DOES FORM VALIDATION  - OmarAA
function ValidateForm(elValue, errForm, regexFormVld, arrFormRange, errregexFormReq, errregexFormVld, errregexFormRange)
{
    var validated = true;
    var errValue = "";

    if (arrFormRange[0] != 0)
    {
        // CHECK IF FORM IS EMPTY OR NULL - OmarAA      
        if(elValue == null || elValue == "") {
               validated = false;
               errValue += j$Obj(errregexFormReq).value;
        }
    }

    if (validated == true) {
        // VALIDATE FORM - OmarAA
        
        var regexValue= j$Obj(regexFormVld).value;        
        var re = new RegExp(regexValue);         
        if(!elValue.match(re))
        {
               validated = false;
               errValue += j$Obj(errregexFormVld).value;
        }
        
        // VALIDATE LENGTH - OmarAA
        if (((elValue.length < arrFormRange[0]) || (elValue.length > arrFormRange[1])) && validated == true)
        {
               validated = false;
               errValue += j$Obj(errregexFormRange).value;
        } 
    }
    
    // IF VALIDATED DO WORK USING AJAX, IF NOT THEN SHOW ERROR MESSAGE - OmarAA
    if(validated == true) {
        return true;
        j$Obj(errForm).innerHTML = "";
    } else {
       j$Obj(errForm).innerHTML = errValue;
       return false;
    }
} 


// THIS FUNCTION IS CALLED FIRST, IT CALLS THE AJAX FUNCTION THAT GETS THE MD5 FOR THE
// ENTERED TEXT
function AddComment(BcFileID, BcType) {
    
    j$Obj('errformCommentText').innerHTML = "";

    var formvalid = ValidateformCommentTextInc();
    
    // ADD THE COMMENT
    if (formvalid)
    {
        funcAddComment(BcFileID, BcType, j$Obj(formCommentText).value);
    }
}


// THE FUNCTION THAT ADDS THE COMMENT
function funcAddComment(BcFileID, BcType, CommentText)
{
    var FilesAJAX = new JeeranRemoteScripting();
	FilesAJAX.SetRequestMethod("POST");
	FilesAJAX.SetRequestURL(AddCommentAjaxUrl);
	FilesAJAX.SetData("fileid=" + BcFileID + "&bctype=" + BcType + "&action=addcomment&commentstype=forfile&CommentText=" + CommentText);
	//FilesAJAX.SetRequestURL(AddCommentAjaxUrl + "&fileid=" + BcFileID + "&bctype=" + BcType + "&action=addcomment&commentstype=forfile&CommentText=" + CommentText);
	//FilesAJAX.SetData("");
	FilesAJAX.SetRequestAsynch(true);
    FilesAJAX.InitializeRequester();
    
    ShowDiv('LoadingDiv'); 
    //j$Obj(formCommentText).value = "Adding comment";
    j$Obj(formCommentText).disabled = true;
    j$Obj('btnAddComment').disabled = true;
    
    FilesAJAX.SendRequest();
	//waiting?

	FilesAJAX.OnLoaded = function() {
        var AddCommentSuccess = FilesAJAX.GetText();
        var NewComments;
        
        HideDiv('LoadingDiv');
         
        //CLEAR THE FORMS
        j$Obj(formCommentText).value = "";
        j$Obj('errformCommentText').innerHTML = "";
        
        //ShowDiv('divSuccessForComment');
        //j$Obj('divSuccessForComment').innerHTML = AddCommentSuccess;           
       
        j$Obj(formCommentText).disabled = false;
        j$Obj('btnAddComment').disabled = false;        
        
        // Insert the  new comment
//        NewComments = j$Obj('NewComments').innerHTML;
//        j$Obj('NewComments').innerHTML = AddCommentSuccess + NewComments;
            j$Obj(CommentsNumber).innerHTML=  parseInt(j$Obj(CommentsNumber).innerHTML) + 1;
            HideDiv('FileComments');
            HideDiv('NewComments');
            j$Obj('divMyCommentsFromInc').innerHTML = AddCommentSuccess;

	    FilesAJAX = null;
	}
	FilesAJAX.OnFailure = function() {
        HideDiv('LoadingDiv'); 
        FilesAJAX = null;
        return "Failure";
	}
}

// THE FUNCTION for comments pagging
function CommentsPagging(StartIndex, PageSize,FileId)
{
    var FilesAJAX = new JeeranRemoteScripting();
	FilesAJAX.SetRequestMethod("POST");
	FilesAJAX.SetRequestURL(CommentsPaggingAjaxUrl);
	FilesAJAX.SetData("fileid=" + FileId +  "&action=list&page=" +CurrentPage + "&startindex=" + StartIndex +"&pagesize=" + PageSize);
	FilesAJAX.SetRequestAsynch(true);
    FilesAJAX.InitializeRequester();
    
    FilesAJAX.SendRequest();

    ShowDiv('LoadingDiv');
    
	FilesAJAX.OnLoaded = function() {
        var CommentsPaggingSuccess = FilesAJAX.GetText();
        var NewComments;
        
        HideDiv('LoadingDiv');

            HideDiv('FileComments');
            HideDiv('NewComments');
            

            j$Obj('divMyCommentsFromInc').innerHTML = CommentsPaggingSuccess;

        
	    FilesAJAX = null;
	}
	FilesAJAX.OnFailure = function() {
        HideDiv('LoadingDiv'); 
        FilesAJAX = null;
        return "Failure";
	}
}


// FUNCTION THAT CALLS DOES FORM VALIDATION FOR ADDING A TAG - OmarAA
function ValidateformCommentTextInc()
{
    // GET Comment VALUE - OmarAA
    var elValue= j$Obj(formCommentText).value;
    var validated = true;
    var errValue = "";

    //Remove empty spaces
    elValue = elValue.replace(/(^\s+)(\s+$)/, "");

    //Strip HTML Tags
    elValue = stripHTMLTags(elValue);
   j$Obj(formCommentText).value = elValue;    

    // CHECK IF Comment IS EMPTY OR NULL - OmarAA
    if(elValue == null || elValue == "" || elValue== AddCommentWaterMark) {
           validated = false;
           errValue += j$Obj('vldCommentTextRequired').value;
    }

    if (validated == true) {
        // VALIDATE Comment - OmarAA
        var regexValue= j$Obj('RegExvldCommentText').value;        
        var re = new RegExp(regexValue);
              
        if(!elValue.match(re))
        {
               validated = false;
               errValue += j$Obj('vldCommentText').value;
        }
        
        // VALIDATE LENGTH - OmarAA
        if ((elValue.length < 3) || (elValue.length > 500))
        {
               validated = false;
               errValue += j$Obj('vldCommentTextRange').value;
        } 
    }

    // IF VALIDATED ADD THE Comment USING AJAX, IF NOT THEN SHOW ERROR MESSAGE - OmarAA
    if(validated == false) {
       j$Obj('errformCommentText').innerHTML = errValue;
    }
    return validated;
}

function ShowTheAddCommentDiv()
{
    ShowDiv('pnlCommentForm');
    j$Obj('divSuccessForComment').innerHTML = "";
    HideDiv('divSuccessForComment');
    j$Obj('OwnerOptionsTab4').style.backgroundColor = "#fff";
}

function HighLightDiv(DivName) {
	 j$Obj(DivName).style.background= "#FFFFE4";
}

function UnHighLightDiv(DivName) {
	 j$Obj(DivName).style.background= "";
}

// Comments
// THE FUNCTION THAT GETS THE COMMENT
function funcGetFileComments()
{
    var CommentsAJAX = new JeeranRemoteScripting();
	CommentsAJAX.SetRequestMethod("GET");
	CommentsAJAX.SetRequestURL(CommentsAjaxUrl + '&action=list' + '&commentstype=forfile');
	CommentsAJAX.SetData("");
	CommentsAJAX.SetRequestAsynch(true);
    CommentsAJAX.InitializeRequester();
	
	//ShowDiv('tabLoadingShowComments');
	
	CommentsAJAX.SendRequest();
	//waiting?

	CommentsAJAX.OnLoaded = function() {    
        j$Obj('FileComments').innerHTML = CommentsAJAX.GetText();
	    CommentsAJAX = null;
	    //HideDiv('tabLoadingShowComments');
	}
	CommentsAJAX.OnFailure = function() {
	    CommentsAJAX = null;
	    //HideDiv('tabLoadingShowComments');
	    j$Obj('FileComments').innerHTML = "Failure";
	}
}

// THE FUNCTION THAT GETS THE COMMENT
function funcDeleteFileComment(FileID,CommentID)
{
    if (ConfirmDeleteComment()) {
        
        var DeleteCommentsAJAX = new JeeranRemoteScripting();
	    DeleteCommentsAJAX.SetRequestMethod("GET");
	    DeleteCommentsAJAX.SetRequestURL(AddCommentAjaxUrl + '&action=deletecomment' + '&commentid=' + CommentID + '&commentstype=forfile' 
	                                     + '&fileid=' + FileID
	                                     + "&page=" + CurrentPage );
	    DeleteCommentsAJAX.SetData("");
	    DeleteCommentsAJAX.SetRequestAsynch(true);
        DeleteCommentsAJAX.InitializeRequester();
        ShowDiv('LoadingDiv');
	    DeleteCommentsAJAX.SendRequest();
	    //waiting?

	    DeleteCommentsAJAX.OnLoaded = function() {
            HideDiv('LoadingDiv');
            HideDiv('FileComments');
            HideDiv('NewComments');
            j$Obj('divMyCommentsFromInc').innerHTML = DeleteCommentsAJAX.GetText();
            j$Obj(CommentsNumber).innerHTML=  parseInt(j$Obj(CommentsNumber).innerHTML) - 1;
	        DeleteCommentsAJAX = null;
	    }
	    DeleteCommentsAJAX.OnFailure = function() {
	        HideDiv('LoadingDiv');
	        DeleteCommentsAJAX = null;
	        	     
//	        j$Obj('divMyCommentsFromInc').innerHTML = "Failure";
	    }
	}
}

function funcApproveFileComment(FileIDx,CommentID)
{
    if (ConfirmApproveComment()) {
        var ApproveCommentsAJAX = new JeeranRemoteScripting();
	    ApproveCommentsAJAX.SetRequestMethod("GET");
	    ApproveCommentsAJAX.SetRequestURL(CommentsAjaxUrl + '&action=approvecomment' + '&commentid=' + CommentID + '&commentstype=forfile');
	    ApproveCommentsAJAX.SetData("");
	    ApproveCommentsAJAX.SetRequestAsynch(true);
        ApproveCommentsAJAX.InitializeRequester();
	        ShowDiv('tabLoadingShowComments');
	    ApproveCommentsAJAX.SendRequest();
	    //waiting?

	    ApproveCommentsAJAX.OnLoaded = function() {
	        HideDiv('tabLoadingShowComments');
            j$Obj('divMyCommentsFromInc').innerHTML = ApproveCommentsAJAX.GetText();
	        ApproveCommentsAJAX = null;
	    }
	    ApproveCommentsAJAX.OnFailure = function() {
	        HideDiv('tabLoadingShowComments');
	        ApproveCommentsAJAX = null;
	        j$Obj('divMyCommentsFromInc').innerHTML = "Failure";
	    }
    }
}

function ConfirmDeleteComment(){
    return window.confirm(txtConfirmDeleteComment);
}

function ConfirmApproveComment(){
    return window.confirm(txtConfirmApproveComment);
}

/*Sidebar*/
function ToggleMoreInfo(ImageID, LayerID)
{
    toggle(LayerID);
    toggleImage(ImageID, "/im/j2/site/images/grey_arrow_rt.gif", "/im/j2/site/images/grey_arrow_dn.gif");
}

// TAGS Box
// This function takes the user to view a given tag
function SeeTag(TagText)
{
    window.location = replace(TagsUrl, "||TAG||", TagText);
}

// ShowEditChannels
function EditChannels()
{
    ShowDiv('OwnerChannelsEditBox');
    HideDiv('OwnerChannelsBox');
    j$Obj('ChannelsEditLink').style.display = 'none';
    j$Obj('ChannelsDoneLink').style.display = 'inline';
}

function EditChannelsDone(FileID)
{

    SaveChannelsChanges(FileID);
    HideDiv('OwnerChannelsEditBox');
    ShowDiv('OwnerChannelsBox');
    j$Obj('ChannelsEditLink').style.display = 'inline';
    j$Obj('ChannelsDoneLink').style.display = 'none';
}

function SaveChannelsChanges(FileID)
{
    var FileChannels= GetSelected(lstChannels);
    var FileChannelsSettingsAJAX = new JeeranRemoteScripting();
    if (FileChannels != "")
    {
	    FileChannelsSettingsAJAX.SetRequestMethod("POST");
	    FileChannelsSettingsAJAX.SetRequestURL(FileChannelsSettingsAJAXURL);
	    FileChannelsSettingsAJAX.SetData('fileid=' + FileID + '&UpdateChannels=true&category=' + FileChannels);
    	
	    FileChannelsSettingsAJAX.SetRequestAsynch(true);	
	    FileChannelsSettingsAJAX.InitializeRequester();

    	
	    FileChannelsSettingsAJAX.SendRequest();
	}
	
	

	FileChannelsSettingsAJAX.OnLoaded = function() {
	
    
    var selectedText = GetSelectedText(lstChannels).split(",");
    if (selectedText != "")
    {
        document.getElementById("selectedChannels").innerHTML = selectedText;
    }
 
	}
	FileChannelsSettingsAJAX.OnFailure = function() {
		
	}	

    
}

function GetSelectedText(item)
{
    var len = j$Obj(item).length;
    var i = 0;
    var selectedItems = "";
    for (i = 0; i < len; i++)
    {
        if (j$Obj(item)[i].selected) 
        {
            if(j$Obj(item)[i].value != "0")
            {
                selectedItems = selectedItems + j$Obj(item)[i].text + " ";    
            }
         }
    }
    selectedItems = rtrim(selectedItems, ',')

    return selectedItems;
} 

function GetSelected(item)
{
    var len = j$Obj(item).length;
    var i = 0;
    var selectedItems = "";
    for (i = 0; i < len; i++)
    {
        if (j$Obj(item)[i].selected) 
        {
            if(j$Obj(item)[i].value != "0")
            {
                selectedItems = selectedItems + j$Obj(item)[i].value + ",";    
            }
         }
    }
    selectedItems = rtrim(selectedItems, ',')

    return selectedItems;
} 


// ShowEditTags
function EditTags()
{
    ShowDiv('OwnerTagsEditBox');
    HideDiv('OwnerTagsBox');
    j$Obj('TagsEditLink').style.display = 'none';
    j$Obj('TagsDoneLink').style.display = 'inline';
    ShowDiv('AddTagsForm');
}



function EditTagsDone()
{
    HideDiv('OwnerTagsEditBox');
    ShowDiv('OwnerTagsBox');
    j$Obj('TagsEditLink').style.display = 'inline';
    j$Obj('TagsDoneLink').style.display = 'none';
    HideDiv('AddTagsForm');
}

// AJAX FUNCTION THAT GETS THE FILES - OmarAA
function funcGetFileTagsForInc(AddTag, DeleteTag) {
	var FilesAJAX = new JeeranRemoteScripting();
	FilesAJAX.SetRequestMethod("POST");
	FilesAJAX.SetRequestURL(GetTagsAjaxUrl + '&deletetag=' + DeleteTag);
	FilesAJAX.SetData("addtag=" + AddTag);
	FilesAJAX.SetRequestAsynch(true);	
	FilesAJAX.InitializeRequester();
	
    if (AddTag != '' || DeleteTag != '')
    { 
        ShowDiv('tabLoadingTags'); 
    }
        
	FilesAJAX.SendRequest();
	
	FilesAJAX.OnLoaded = function() {
	    if (AddTag != '' || DeleteTag != '')
        { HideDiv('tabLoadingTags'); }
        DisplayFileTagsForInc(FilesAJAX.GetText());
        if (AddTag != '' && AddTag != null)
        { 
            var myTags = j$Obj('hdnAddedTags').innerHTML;
            if (myTags != '' && myTags != null)
            { 
                var arrTags=myTags.split(",");
                for (var i=0; i < arrTags.length; i++)
                {
                    j$Obj('myTr_' + arrTags[i]).style.visibility = "visible";
                    opacity('myTr_' + arrTags[i], 70, 0, 5000); 
                    
                    //setTimeout('HideDiv(\'myTr_' + arrTags[i] + '\')',6000);
                }
            }
        }
           j$Obj('TagsDoneLink').style.display = 'inline';
	}
	
	FilesAJAX.OnFailure = function() {
		DisplayFileTagsForInc("Failure");
		if (AddTag != '' || DeleteTag != '')
        { HideDiv('tabLoadingTags'); }
		//alert("Failed");
	}	
}

// FUNCTION THAT WRITE THE AJAX RESULT TO THE DIV - OmarAA
function DisplayFileTagsForInc(htmlResult) {
    j$Obj('DivFileTagsForInc').innerHTML = htmlResult;
}

// FUNCTION THAT CALLS THE AJAX FUNCTION FOR ADDING A TAG - OmarAA
function funcAddTag(TagText) {
    funcGetFileTagsForInc(TagText, '');
}

// FUNCTION THAT CALLS THE AJAX FUNCTION FOR DELETING A TAG - OmarAA
function funcDeleteTag(TagText) {
    if(ConfirmTagDelete()) 
    {
        funcGetFileTagsForInc('', TagText); 
    }
}

function ConfirmTagDelete(){
    return window.confirm(txtConfirmDeleteTag);
}

// FUNCTION THAT CALLS DOES FORM VALIDATION FOR ADDING A TAG - OmarAA
function ValidateformTagTextInc()
{
    // GET TAG VALUE - OmarAA
    var elValue= j$Obj('formTagTextInc').value;

    var validated = true;
    var errValue = "";

    // CHECK IF TAG IS EMPTY OR NULL - OmarAA
    if(elValue == null || elValue == "") {
           validated = false;
           errValue += j$Obj('vldTagTextRequired').value;
    }
   
    // IF VALIDATED ADD THE TAG USING AJAX, IF NOT THEN SHOW ERROR MESSAGE - OmarAA
    if(validated == true) {
        funcAddTag(elValue);
        j$Obj('errformTagTextInc').innerHTML = "";
        j$Obj('formTagTextInc').value = "";
    } else {
       j$Obj('errformTagTextInc').innerHTML = errValue;
    }
    return false;
}

// KEY PRESS ON A TEXTBOX DOES NOT SUBMIT THE PAGE - OMAR AA
function TagKeyPress(e, field) {
    var oEvent = window.event ? window.event : e;

    var isDOM = (j$Obj ? true : false);
    var isNS4 = (document.layers ? true : false);

    if (document.all != 'undefined') key = oEvent.keyCode;
    else if (isDOM) key = oEvent.charCode;
    else if (isNS4) key = oEvent.which;

    if (key == 13)
    {
        ValidateformTagTextInc();
        oEvent.cancelBubble = true;
        return false;
    }
    else
    { 
        return true; 
    }
}

/*Link*/
function SelectLink(Control)
{
    Control.select();
}

/*Embed*/
function ShowEmbedCode() {
    //j$Obj("FileEmbed").innerHTML = j$Obj(flvPlayerID).innerHTML;
}

function SelectEmbed() {
    j$Obj("FileEmbed").select();
}

function GetSelectedItems()
{
    var len = j$Obj("lstCategories").length;
    var i = 0;
    var selectedItems = "";
    for (i = 0; i < len; i++)
    {
        if (j$Obj("lstCategories")[i].selected) 
        {
            if(j$Obj("lstCategories")[i].value != "0")
            {
                selectedItems = selectedItems + j$Obj("lstCategories")[i].value + ",";    
            }
         }
    }
    selectedItems = rtrim(selectedItems, ',')

    return selectedItems;
} 



function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*Task Bar*/
function SaveFileSettings()
{
    var FilePublic, AllowComments, ShowComments,FileCategory;    
    
    var dropdownIndex = j$Obj("lstCategories").selectedIndex
    
    FileCategory = GetSelectedItems();
    
    //check whether the user chose a category type or not.
    if(FileCategory == "")
    {    
        j$Obj("errCategory").style.display = 'block';
        
        return false;
    }
    
    if(j$Obj("formFilePrivacy0").checked)
    {
        FilePublic = 0;
    }
    else if (j$Obj("formFilePrivacy1").checked)
    {
        FilePublic = 1;
    }
    else if (j$Obj("formFilePrivacy2").checked)
    {
        FilePublic = 2;
    }
    
    if(j$Obj("formAllowComments0").checked)
    {
        AllowComments = 0;
    }
    else if (j$Obj("formAllowComments1").checked)
    {
    
        AllowComments = 1;
    }   
    
    if(j$Obj("formShowComments0").checked)
    {
        ShowComments = 0;
    }
    else if (j$Obj("formShowComments1").checked)
    {
        ShowComments = 1;
    }
    
    SetFileSettings(FilePublic, AllowComments, ShowComments,FileCategory);     
}

// AJAX FUNCTION THAT SETS THE FILE SETTINGS
function SetFileSettings(FilePublic, AllowComments, ShowComments,FileCategory ) {
	var FileSettingsAJAX = new JeeranRemoteScripting();
	FileSettingsAJAX.SetRequestMethod("POST");
	FileSettingsAJAX.SetRequestURL(AjaxFileSettingsUrl);
	FileSettingsAJAX.SetData('fileid=' + FileID + '&filepublic=' + FilePublic+ '&allowcomments=' + AllowComments+ '&showcomments=' + ShowComments +'&category=' + FileCategory);
	
	//alert('fileid=' + FileID + '&filepublic=' + FilePublic+ '&allowcomments=' + AllowComments+ '&showcomments=' + ShowComments);
	
	FileSettingsAJAX.SetRequestAsynch(true);	
	FileSettingsAJAX.InitializeRequester();
	
	ShowDiv('tabLoadingFileSettings');
	
	FileSettingsAJAX.SendRequest();
	
	//waiting?
	FileSettingsAJAX.OnLoaded = function() {
        DisplayFileSettingsSuccessForInc(FileSettingsAJAX.GetText());
        HideDiv('tabLoadingFileSettings');
	}
	FileSettingsAJAX.OnFailure = function() {
		DisplayFileSettingsSuccessForInc("Failure");
		HideDiv('tabLoadingFileSettings');
	}	
}

function DeleteFile(fileId)
{

    var FileDeleteAJAX = new JeeranRemoteScripting();
	FileDeleteAJAX.SetRequestMethod("POST");
	FileDeleteAJAX.SetRequestURL(FileDeleteAJAXURL);
	FileDeleteAJAX.SetData('fileid=' + fileId + '&eventurl=' + escape(EventPageURL));

	FileDeleteAJAX.SetRequestAsynch(true);	
	FileDeleteAJAX.InitializeRequester();

	
	FileDeleteAJAX.SendRequest();
	
	//waiting?
	FileDeleteAJAX.OnLoaded = function() {

	}
	FileDeleteAJAX.OnFailure = function() {

	}	
}

function DisplayFileSettingsSuccessForInc(htmlResult) {
    //HideDiv('pnlEditFileOptions');
    ShowDiv('divFileSettingsSuccess');
    document.getElementById('divFileSettingsSuccess').innerHTML = htmlResult;
}

function funcBtnOKSuccessSetFileSettings() {
    funcCancelbtn();
}

function ClearTheShareWithFriendsForm() {
    document.getElementById('errformSetShareUserID').innerHTML = "";
    document.getElementById('formSetShareUserID').value = "";
}

function ClearTheSendToFriendDiv()
{
    HideDiv('DiverrformSendToFriendAllEmpty');
    document.getElementById('formSendToFriendFriendName_1').value = "";
    document.getElementById('formSendToFriendFriendEmail_1').value = "";
    document.getElementById('formSendToFriendFriendName_2').value = "";
    document.getElementById('formSendToFriendFriendEmail_2').value = "";
    document.getElementById('formSendToFriendFriendName_3').value = "";
    document.getElementById('formSendToFriendFriendEmail_3').value = "";

    document.getElementById('errformSendToFriendFriendName_1').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_1').innerHTML = "";
    document.getElementById('errformSendToFriendFriendName_2').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_2').innerHTML = "";
    document.getElementById('errformSendToFriendFriendName_3').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_3').innerHTML = "";
}

function ValidateSendToFriend()
{
    HideDiv('DiverrformSendToFriendAllEmpty');
    document.getElementById('errformSendToFriendFriendName_1').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_1').innerHTML = "";
    document.getElementById('errformSendToFriendFriendName_2').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_2').innerHTML = "";
    document.getElementById('errformSendToFriendFriendName_3').innerHTML = "";
    document.getElementById('errformSendToFriendFriendEmail_3').innerHTML = "";

    var ValidFriendName_1 = true;
    var ValidFriendEmail_1 = true;
    var ValidFriendName_2 = true;
    var ValidFriendEmail_2 = true;
    var ValidFriendName_3 = true;
    var ValidFriendEmail_3 = true;

    var elValueFriendName_1 = document.getElementById('formSendToFriendFriendName_1').value;
    var elValueFriendEmail_1 = document.getElementById('formSendToFriendFriendEmail_1').value;
    var elValueFriendName_2 = document.getElementById('formSendToFriendFriendName_2').value;
    var elValueFriendEmail_2 = document.getElementById('formSendToFriendFriendEmail_2').value;
    var elValueFriendName_3 = document.getElementById('formSendToFriendFriendName_3').value;
    var elValueFriendEmail_3 = document.getElementById('formSendToFriendFriendEmail_3').value;

    var EmptyForm1 = true;
    var EmptyForm2 = true;
    var EmptyForm3 = true;

    if (!((elValueFriendName_1 == "" || elValueFriendName_1 == null) && (elValueFriendEmail_1 == "" || elValueFriendEmail_1 == null)))
    {
        ValidFriendName_1 = ValidateForm(elValueFriendName_1,'errformSendToFriendFriendName_1','RegExvldSendToFriendName',new Array("3", "50"),'vldSendToFriendNameErrRequired','vldSendToFriendNameErr','vldSendToFriendNameErrRange');
        ValidFriendEmail_1 = ValidateForm(elValueFriendEmail_1,'errformSendToFriendFriendEmail_1','RegExvldSendToFriendEmail',new Array("5", "50"),'vldSendToFriendEmailErrRequired','vldSendToFriendEmailErr','vldSendToFriendEmailErrRange');
        EmptyForm1 = false;
    }
    if (!((elValueFriendName_2 == "" || elValueFriendName_2 == null) && (elValueFriendEmail_2 == "" || elValueFriendEmail_2 == null)))
    {
        ValidFriendName_2 = ValidateForm(elValueFriendName_2,'errformSendToFriendFriendName_2','RegExvldSendToFriendName',new Array("3", "50"),'vldSendToFriendNameErrRequired','vldSendToFriendNameErr','vldSendToFriendNameErrRange');
        ValidFriendEmail_2 = ValidateForm(elValueFriendEmail_2,'errformSendToFriendFriendEmail_2','RegExvldSendToFriendEmail',new Array("5", "50"),'vldSendToFriendEmailErrRequired','vldSendToFriendEmailErr','vldSendToFriendEmailErrRange');
        EmptyForm2 = false;
    }
    if (!((elValueFriendName_3 == "" || elValueFriendName_3 == null) && (elValueFriendEmail_3 == "" || elValueFriendEmail_3 == null)))
    {
        ValidFriendName_3 = ValidateForm(elValueFriendName_3,'errformSendToFriendFriendName_3','RegExvldSendToFriendName',new Array("3", "50"),'vldSendToFriendNameErrRequired','vldSendToFriendNameErr','vldSendToFriendNameErrRange');
        ValidFriendEmail_3 = ValidateForm(elValueFriendEmail_3,'errformSendToFriendFriendEmail_3','RegExvldSendToFriendEmail',new Array("5", "50"),'vldSendToFriendEmailErrRequired','vldSendToFriendEmailErr','vldSendToFriendEmailErrRange');
        EmptyForm3 = false;
    }
    if (EmptyForm1 == false || EmptyForm2 == false || EmptyForm3 == false)
    {
        if (ValidFriendName_1 == true && ValidFriendEmail_1 == true && ValidFriendName_2 == true && ValidFriendEmail_2 == true && ValidFriendName_3 == true && ValidFriendEmail_3 == true)
            {
                funcSendEmail(elValueFriendName_1,elValueFriendEmail_1,elValueFriendName_2,elValueFriendEmail_2,elValueFriendName_3,elValueFriendEmail_3);
            }
    }
    else
    {
        ShowDiv('DiverrformSendToFriendAllEmpty');
        document.getElementById('DiverrformSendToFriendAllEmpty').innerHTML = document.getElementById('errformSendToFriendAllEmpty').value;
    }
}

   
// THE FUNCTION THAT ADDS THE COMMENT
function funcSendEmail(ReceiverName_1,ReceiverEmail_1,ReceiverName_2,ReceiverEmail_2,ReceiverName_3,ReceiverEmail_3)
{
    var FilesAJAX = new JeeranRemoteScripting();
	FilesAJAX.SetRequestMethod("POST");
	FilesAJAX.SetRequestURL(AjaxSendFileUrl + '&action=' + sendFileEmailAction);
	FilesAJAX.SetData("FileID=" + FileID +
            "&ReceiverEmail_1=" + ReceiverEmail_1 +
            "&ReceiverName_1=" + ReceiverName_1 +
            "&ReceiverEmail_2=" + ReceiverEmail_2 +
            "&ReceiverName_2=" + ReceiverName_2 +
            "&ReceiverEmail_3=" + ReceiverEmail_3 +
            "&ReceiverName_3=" + ReceiverName_3);
	
	
	FilesAJAX.SetRequestAsynch(true);
    FilesAJAX.InitializeRequester();
        ShowDiv('tabLoadingFileSendToFriend');
	FilesAJAX.SendRequest();
	//waiting?

	FilesAJAX.OnLoaded = function() {
        FilesAJAX.GetText();
        
        ClearTheSendToFriendDiv();
        HideDiv('pnlSendToFriendForm');
        ShowDiv('pnlSucceesSendToFriend');
            HideDiv('tabLoadingFileSendToFriend');
	    FilesAJAX = null;
	}
	FilesAJAX.OnFailure = function() {
	        FilesAJAX = null;
	        HideDiv('tabLoadingFileSendToFriend');
	        return "Failure";
	}
}

function funcBtnOKSuccessSendToFriend() {
    funcCancelbtn();
}

//Updates File description - NawwarG 26.04.2009
function UpdateFileDescription(description)
{

}


//Pulse.js

// Constructs the Query string to be passed to the Ajax Page.
function ConstructQueryString(Filter,Type,View, divName)
{
    var QueryString;
    
    QueryString =  "filter=" + Filter;  
    QueryString +=  "&type="+ Type;  
    QueryString +=  "&view="+ View;  
 
    if( view == 'neighbors')
    {
        document.getElementById('lnkNeighbors').className = 'selected';
        document.getElementById('lnkEveryone').className = '';
    }
    else
    {
        document.getElementById('lnkEveryone').className = 'selected';
        document.getElementById('lnkNeighbors').className = '';
    }
     
    switch(filter)
    {
        case 'new':
            
            if(Type == 'videos')
            {
                document.getElementById('lnkViewVideos').className = 'selected';
                
            }
            else
            {
                document.getElementById('lnkViewPhotos').className = 'selected';
            }
            
            document.getElementById('lnkViewComments').className = ' ';
            document.getElementById('lnkViewAll').className = ' ';
        break;
        
        case 'comments':
            document.getElementById('lnkViewComments').className = 'selected';
            document.getElementById('lnkViewAll').className = ' ';
            
            if(Type == 'videos')
            {
                document.getElementById('lnkViewVideos').className = ' ';
                
            }
            else
            {
                document.getElementById('lnkViewPhotos').className = ' ';
            }
            
        break;
        
        default:
            document.getElementById('lnkViewAll').className = 'selected';
            document.getElementById('lnkViewComments').className = ' ';

            if(Type == 'videos')
            {
                document.getElementById('lnkViewVideos').className = ' ';
                
            }
            else
            {
                document.getElementById('lnkViewPhotos').className = ' ';
            }
            
        break;
    }

    CallAjaxPage(QueryString, divName);
}

//Calls an Ajax page that gets the events  - MAISQ -
function CallAjaxPage(QueryString, divName) 
{
    try
    { 
        NfAjaxRequest.Close();
    }
    catch(error)
    {
    }
    
    NfAjaxRequest = CreateAjaxRequest(PageURL , 'POST', QueryString);
        
    SetTextOfLayer(divName, "<div style='position: relative; top:40px; margin: auto; height:31px; width:150px; line-height:31px; font-size: 10px;'><img src='/im/j2/ajax/loading.gif' style='height: auto; width: auto; border:0; padding:0;' />&nbsp;" + nfLoadingText + "</div>");
    
    NfAjaxRequest.OnLoaded = function()
    {
        SetTextOfLayer(divName, NfAjaxRequest.GetText());
        NfAjaxRequest = null;
    }

    NfAjaxRequest.OnFailure = function()
    {
        ErrorMsg = "Load failed. Please try again!";
        SetTextOfLayer(divName, ErrorMsg);
        NfAjaxRequest = null;   
    }
}


//ShareFunctions.js
formMyFriends = "FriendsList";
formSharedTo = "SharedToList";

function GetSharedList()
{
    //formSharedTo
    
}

// AJAX FUNCTION THAT SHARES A FILE
function funcShareFilesAutoSetForInc(BcShareToUserID, action, from, bctype) {
    document.getElementById('errformSetShareUserID').innerHTML = "";
    
	var FileAutoSetAJAX = new JeeranRemoteScripting();
	FileAutoSetAJAX.SetRequestMethod("POST");
	FileAutoSetAJAX.SetRequestURL(AjaxShareFileUrl);
	FileAutoSetAJAX.SetData('bctype=' + bctype + '&fileid=' + FileID + '&user=' + BcShareToUserID + '&action=' + action + '&eventurl=' + escape(EventPageURL));
	FileAutoSetAJAX.SetRequestAsynch(true);	
	FileAutoSetAJAX.InitializeRequester();
	ShowDiv('tabLoadingShareToFriends');
	FileAutoSetAJAX.SendRequest();
	
	//waiting?
	FileAutoSetAJAX.OnLoaded = function() {    
        var htmlresponse = FileAutoSetAJAX.GetText();    

        if (htmlresponse == 'Err_FileOwner')
        {
            document.getElementById('errformSetShareUserID').innerHTML = document.getElementById('vldformSetShareUserIDFileOwner').value;
        }        
        else if (htmlresponse == 'Err_UserNotExist')
        {
            document.getElementById('errformSetShareUserID').innerHTML = document.getElementById('vldformSetShareUserIDErrNotExist').value;
        }
        else
        {
            if(from=='notfriend')
            {
                var SharedToList = j$Obj(formSharedTo);	    
                OptionValue = SharedToList.length;
                OptionText = document.getElementById('formSetShareUserID').value;
                SharedToList.options[SharedToList.length] = new Option(OptionText, OptionValue, false, false);        
                document.getElementById('formSetShareUserID').value = "";
            }         
        }
        	
        HideDiv('tabLoadingShareToFriends');
	}
	
	FileAutoSetAJAX.OnFailure = function() {
	    HideDiv('tabLoadingShareToFriends');
	}	

}

function funcBtnOKSuccessAddUser() {
    funcCancelbtn();
}

function AddUser(bctype) {
   var FriendsList = j$Obj(formMyFriends);
   
    
    for(var i=0; i < FriendsList.length; i++)
    {                    
        if(FriendsList.options[i].selected)
        {
            funcShareFilesAutoSetForInc(FriendsList.options[i].text, 'share', '',bctype);             
            var Index = FriendsList.selectedIndex;            
            MoveListItem(formMyFriends, formSharedTo, "", Index);            
            // always set the first item    
            SelectFirstListItem(formMyFriends);         
        }
    }
}

// Checks if a user has been selected from the list,
// sends the ajax request to remove the user
// then moves the users from the share list to the friends list
function RemoveUser() {
    var SharedToList = j$Obj(formSharedTo); 
    
    for(var i=0; i < SharedToList.length; i++)
    {                    
        if(SharedToList.options[i].selected)
        {
            funcShareFilesAutoSetForInc(SharedToList.options[i].text, 'unshare','', '');
            var Index = SharedToList.selectedIndex;            
            MoveListItem(formSharedTo, formMyFriends, "", Index);            
            // always set the first item    
            SelectFirstListItem(formSharedTo);         
        }
    } 
} 


function ShareFileWithUser(bctype) {
    j$Obj('errformSetShareUserID').innerHTML = "";
    
    var ValidShareToUserID = ValidateForm(j$Obj('formSetShareUserID').value,'errformSetShareUserID','RegExvldformSetShareUserID',new Array("4", "50"),'vldformSetShareUserIDErrRequired','vldformSetShareUserIDErr','vldformSetShareUserIDErrRange');
    
    
    if (ValidShareToUserID)
    {
        /// CHECK IF THE USER ALREADY EXISTS IN THE SHARED TO LIST - OMAR B
        var SharedToList = j$Obj("SharedToList");

        for(var i=0; i < SharedToList.length; i++)
        {
            if(j$Obj('formSetShareUserID').value == SharedToList[i].text)
            {
                j$Obj('errformSetShareUserID').innerHTML = j$Obj('vldformSetShareUserIDErrAlreadyExist').value;
                return false;
            }
        }
        
        /// CHECK IF THE USER ALREADY EXISTS IN MY FRIENDS LIST - OMAR B
        var FriendsList = j$Obj("FriendsList");

        for(var i=0; i < FriendsList.length; i++)
        {
            if(j$Obj('formSetShareUserID').value == FriendsList[i].text)
            {
                j$Obj('errformSetShareUserID').innerHTML = j$Obj('vldformSetShareUserIDErrAlreadyExist').value;
                return false;
            }
        }        
        
        funcShareFilesAutoSetForInc(document.getElementById('formSetShareUserID').value, 'share', 'notfriend', bctype);
    }
}

//swfobject.js
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

//Tags.js
function AddCurrentTag(ControlID)
    {
        var QueryString;
        var newTagsText = document.getElementById(ControlID).value;
        var currentTagsText = document.getElementById('lblHiddenCurrentTags');
            
        if((newTagsText === undefined) || (newTagsText == ''))
        {
            newTagsText = document.getElementById(ControlID).innerHTML;
            //document.getElementById(ControlID).href = 'javascript:void(0)';
        }
        else
        {
          newTagsText = stripHTMLTags(newTagsText);
        }

        QueryString =  "newtags=" + newTagsText;  
        QueryString +=  "&action=add";
        
        if(currentTagsText != null)
        {
            QueryString +=  "&currenttags=" + currentTagsText.value;
        }
        
        CallTagsAjaxPage(QueryString, divTags);
        
        document.getElementById(ControlID).value = '';
        
    }
        
//Calls an Ajax page that gets the events  - MAISQ -
function CallTagsAjaxPage(QueryString, divName) 
{
    TagsAjaxRequest = CreateAjaxRequest(TagsUrl , 'POST', QueryString);
        
    SetTextOfLayer(divName, "<div class='bc_loading'><img src='/im/j2/ajax/loading.gif' style='height: auto; width: auto; border:0; padding:0;' />&nbsp;" + loadingText + "</div>");
    
    TagsAjaxRequest.OnLoaded = function()
    {
       SetTextOfLayer(divName, TagsAjaxRequest.GetText());
       document.getElementById(lblFileHTML).value = TagsAjaxRequest.GetText();
       TagsAjaxRequest = null;
       
       var fileTags =  document.getElementById('lblHiddenCurrentTags');
       
       if(fileTags != null)
       {
            document.getElementById(lblFileTags).value = fileTags.value;
       }
    }

    TagsAjaxRequest.OnFailure = function()
    {
        ErrorMsg = "Load failed. Please try again!";
        SetTextOfLayer(divName, ErrorMsg);
        TagsAjaxRequest = null;   
    }
}
        
//TODO: SHOULD BE PLACED INSIDE THE MAIN JS LIBRARY BECUASE IT IS A GENERIC METHOD.
function ShowHideDiv(ControlID)
{
    var myDiv = document.getElementById(ControlID);
   
    if(myDiv.style.display == 'block')
    {
       myDiv.style.display="none";
    }
     else
    {
       myDiv.style.display="block";
    }
}
        
function RemoveTag(tag)
{
    var currentTagsText = document.getElementById('lblHiddenCurrentTags');
    var QueryString;
        
    QueryString =  "deltag=" + tag;  
    QueryString +=  "&action=remove";
    
    if(currentTagsText != null)
    {
        QueryString +=  "&newtags=" + currentTagsText.value;
    }
  
    CallTagsAjaxPage(QueryString, divTags);
}

//TODO: THIS IS A GENERIC METHOD, IT SHOULD PLACED SOMEWHERE ELSE.  - MAISQ -
function stripHTMLTags (elValue)
{        
    var re= /<\S[^><]*>/g;
    for (i=0; i<elValue.length; i++)
    {
        elValue=elValue.replace(re,"");
    }
    return elValue;
}


/////////////////////////////////////
    var current=1;
	var GlobImages;
	var GlobTitle;
	var GlobURL;
	var numberofItems;
	var GlobLang="a";
	var GlobType="video";
	
	function RelatedSlider(images,title,url,lang,type)
		{
		
		GlobImages=images;
		GlobTitle=title;
		GlobURL=url;
		GlobLang=lang;
		GlobType=type;
		
		
		numberofItems = GlobImages.length;
		
		
		
		itemSlider("0");
		
		
	}
	 function itemSlider(check)
	 {
		 var relatedHTML="";
		 
		 
		if (GlobType=="video")
		{
		 
		if(current>=1 && current<=Math.ceil(numberofItems/4))
		{
			
		rightArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcRightArrow.gif' /></a>";
		else
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcLeftArrow.gif' /></a>";
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
		
		leftArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcLeftArrow.gif' /></a>";
		else
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcRightArrow.gif' /></a>";
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
		
		relatedHTML="";
		document.getElementById("bcRecommendedUL").innerHTML=relatedHTML;
		
	if (check==-1)
	
	current--;
	
	else if(check==1)
	current++;	
	
	
	if(current==Math.ceil(numberofItems/4))
	{
		rightArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		{
		rightArrowHTML+="";
		}
		else
		rightArrowHTML+="";
		
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
	}
	
	if(current==1)
	{
		leftArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		leftArrowHTML+="";
		else
		leftArrowHTML+="";
		
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
	
	}
		if (current * 4 > numberofItems)
		{
			for(i=(current - 1)*4;i<numberofItems;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumb'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div><div class='bcRecommendedItemTitle'><a class='bcRecommendedItemAnchor' href='" + GlobURL[i] + "'>"+GlobTitle[i]+"</a></div></li>";
				
			}
		}
		
		if (current*4<=numberofItems)
		{
			for(i=(current-1)*4;i<4*current;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumb'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div><div class='bcRecommendedItemTitle'><a class='bcRecommendedItemAnchor' href='" + GlobURL[i] + "'>"+GlobTitle[i]+"</a></div></li>";
				
			}
		}
		}
		}
		
		else if (GlobType=="photo_g")
		{
		document.getElementById("inc_Recommended_divRecommendedVideoMain").style.background="#FAFAFA";
		document.getElementById("bcRecommendedVideoTitle").style.display="none";
		document.getElementById("inc_Recommended_divRecommendedVideoMain").style.border="1px solid #e3e3e3";
		document.getElementById("vedio").style.padding="0 0 20px 0";
		
		
		if(current>=1 && current<=Math.ceil(numberofItems/4))
		{
			
		rightArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcRightArrow_g.gif' /></a>";
		else
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcLeftArrow_g.gif' /></a>";
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
		
		leftArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcLeftArrow_g.gif' /></a>";
		else
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcRightArrow_g.gif' /></a>";
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
		
		relatedHTML="";
		document.getElementById("bcRecommendedUL").innerHTML=relatedHTML;

	if (check==-1)
	
	current--;
	
	else if(check==1)
	current++;	
	
	
	if(current==Math.ceil(numberofItems/4))
	{
		rightArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		{
		rightArrowHTML+="";
		}
		else
		rightArrowHTML+="";
		
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
	}
	
	if(current==1)
	{
		leftArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		leftArrowHTML+="";
		else
		leftArrowHTML+="";
		
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
			
	}
			if (current * 4 > numberofItems)
		{
			for(i=(current - 1)*4;i<numberofItems;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumbPB'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div></li>";
				
			}
		}
		
		if (current*4<=numberofItems)
		{
			for(i=(current-1)*4;i<4*current;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumbPB'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div></li>";
				
			}
		}
		}
			
			
		}
		
		else if (GlobType == "photo_b")
		{
			document.getElementById("bcLeftArrow").style.marginTop="25px";
			document.getElementById("bcRightArrow").style.marginTop="25px";
		 
		if(current>=1 && current<=Math.ceil(numberofItems/4))
		{
			
		rightArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcRightArrow.gif' /></a>";
		else
		rightArrowHTML+="<a href='javascript:itemSlider(1)'><img src='/im/j3/site/bcLeftArrow.gif' /></a>";
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
		
		leftArrowHTML="";
		if(GlobLang == "e" || GlobLang == "f")
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcLeftArrow.gif' /></a>";
		else
		leftArrowHTML+="<a href='javascript:itemSlider(-1)'><img src='/im/j3/site/bcRightArrow.gif' /></a>";
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
		
		relatedHTML="";
		document.getElementById("bcRecommendedUL").innerHTML=relatedHTML;

	if (check==-1)
	
	current--;
	
	else if(check==1)
	current++;	
	
	
	if(current==Math.ceil(numberofItems/4))
	{
		rightArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		{
		rightArrowHTML+="";
		}
		else
		rightArrowHTML+="";
		
		document.getElementById("bcRightArrow").innerHTML=rightArrowHTML;
	}
	
	if(current==1)
	{
		leftArrowHTML="";
		
		if(GlobLang == "e" || GlobLang=="f")
		leftArrowHTML+="";
		else
		leftArrowHTML+="";
		
		document.getElementById("bcLeftArrow").innerHTML=leftArrowHTML;
			
	}
			if (current * 4 > numberofItems)
		{
			for(i=(current - 1)*4;i<numberofItems;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumbPB'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div></li>";
				
			}
		}
		
		if (current*4<=numberofItems)
		{
			for(i=(current-1)*4;i<4*current;i++)
			{
			relatedHTML+="<li class='bcRecommendedItem'>";
			relatedHTML+="<div class='bcRecommendedItemThumbPB'>";
			relatedHTML+="<a href=" + GlobURL[i] + ">";
    		relatedHTML+="<img src=" + GlobImages[i] + "/></a>";
			relatedHTML+="</div></li>";
				
			}
		}
		}
		
		}

			document.getElementById("bcRecommendedUL").innerHTML=relatedHTML;
		 }
		 

function ListFiles(Action,div,FileTitle,FileCategories,OwnerUserID,OwnerID,FileID,Bctype,FileType)
{
    //Construct query string
    //Call Ajax Page
    var QueryString;
    var bcFilesAjaxRequest;
    
    QueryString =  "action=" + Action;  
    QueryString +=  "&title="+ FileTitle;  
    QueryString +=  "&categories="+ FileCategories;  
    QueryString +=  "&ownername="+ OwnerUserID;  
    QueryString +=  "&owner="+ OwnerID;  
    QueryString +=  "&fileid="+ FileID;  
    QueryString +=  "&bctype="+ Bctype;
     QueryString +=  "&filetype="+ FileType;  
    
    try
    { 
        bcFilesAjaxRequest.Close();
    }
    catch(error)
    {        
    }
    
    bcFilesAjaxRequest = CreateAjaxRequest(FileSettingsURL , 'POST', QueryString);

    SetTextOfLayer(div, "<div style='position: relative; top:0px; margin: auto; height:31px; width:150px; line-height:31px; font-size: 10px;text-align:center'><img src='/im/j3/site/loader_s.gif' style='height: auto; width: auto; border:0; padding:0;' />&nbsp;" + nfLoadingText + "</div>");
    
    bcFilesAjaxRequest.OnLoaded = function()
    {        
        var x = bcFilesAjaxRequest.GetText();
        document.getElementById(div).innerHTML = x;        

        if(Action == "recommended")
        {
            var lang = document.getElementById("lang").value;
            var thumbsArr = document.getElementById("thumbsArr").value;
            var linkArr = document.getElementById("linkArr").value;
            var titlesArr = document.getElementById("titlesArr").value;
            var thumbs = thumbsArr.split(",");
            var titles = titlesArr.split(",");
            var links = linkArr.split(",");        
            var filetype = document.getElementById("filetype").value;
            var displayRecTitle = document.getElementById("displayRecTitle").value;
            if(FileType == "photo_g") document.getElementById("RecommendedPhotosTitle").style.display= displayRecTitle;
            RelatedSlider(thumbs,titles,links,lang,filetype);
        }        
        
        bcFilesAjaxRequest = null;        
    }

    bcFilesAjaxRequest.OnFailure = function()
    {
        ErrorMsg = "Load failed. Please try again!";
        SetTextOfLayer(div, ErrorMsg);
        bcFilesAjaxRequest = null;   
    }
}
   