var widthThumbSize = "181"
var heightThumbSize = "131"
var zoom_widthThumbSize = "213"
var zoom_heightThumbSize = "154"
var URL_REQUIRE_LOGIN = "emptyPage.jsp";
var BO_FEATURED_VIDEOS = "bo_featured";
var BO_FEATURED_TEMPLATES = "bo_templates";
var BO_YOUTUBE_VIDEOS = "bo_youtube"; 
var NEWEST_UGC = "newest_ugc";
var confirm = true;
function mainbannerAction(url,target,demo,hit){
     if (url != ""){
          if(target == '_blank'){
             window.open(url);
          }else{
              window.location.href = url; 
          }
     pageTracker._trackPageview('/gizmoz/newsite/home/mainbanner/'+demo+'/'+hit+'/remix'); 
    }       
}
function showDiv(obj){
     var showDiv_obj = document.getElementById(obj);
     if (showDiv_obj){
	showDiv_obj.visible = true; 
	showDiv_obj.style.visibility = 'visible'; 
	showDiv_obj.style.display = 'block'; 
        //alert(obj +" : " + showDiv_obj.style.display);
     }
     else
	 alert('showDiv: div '+obj+' not found');
}
function hideDiv(obj){
     var hideDiv_obj = document.getElementById(obj);
     if (hideDiv_obj){
	hideDiv_obj.visible = false; 
	hideDiv_obj.style.display = 'none';
         //alert(obj +" : "+hideDiv_obj.style.display);
     }
     else
	 alert('hideDiv: div '+obj+' not found');
}
var coordsX = 0;
var coordsY = 0;
function checkCoords(evt){
evt = (evt) ? evt : ((window.event) ? window.event : null);
 if (evt) {
    coordsX = evt.clientX;
    coordsY = evt.clientY;
 }
}
function getMousePosition(ev) {
var posX = ev.clientX - 440/ 2;
var posY = ev.clientY - 180/ 2; 
    var  pos = new Array(posX,posY);
    return pos;
}
function openInfo(divId, titleText, contentText, eve){
    var infoDiv = document.getElementById(divId);
    if(titleText != ''){
    var infoDiv_title = document.getElementById(divId+'_infoTitle');
	infoDiv_title.innerHTML = titleText;
    }
    if(contentText != ''){
    var infoDiv_content = document.getElementById(divId+'_infoContent');
    var divContent = "";
	if(infoDiv_content.innerHTML.indexOf("alertImg") != -1)
	    divContent += '<img src="images/grayStyle/alertImg.png" align="left">';
	divContent += contentText;
	infoDiv_content.innerHTML = divContent;
    }   
   if (eve) { //to show in the plase of click
	var ev = (eve) ? eve : ((window.event) ? window.event : null);
	var positions = getMousePosition(ev);
     }else{ //to show in the center of screen
	var positions = showdeadcenterdiv(440,180,divId);   
     }
	infoDiv.style.left = (positions[0])+'px';
	infoDiv.style.top = (positions[1])+'px';  
	infoDiv.style.display = 'block';
}
function showdeadcenterdiv(Xwidth,Yheight,divid) {
// First, determine how much the visitor has scrolled
var scrolledX, scrolledY;
    if( self.pageYoffset ) {
	scrolledX = self.pageXoffset;
	scrolledY = self.pageYoffset;
    } else if( document.documentElement && document.documentElement.scrollTop ) {
	scrolledX = document.documentElement.scrollLeft;
	scrolledY = document.documentElement.scrollTop;
    } else if( document.body ) {
	scrolledX = document.body.scrollLeft;
	scrolledY = document.body.scrollTop;
    }
// Next, determine the coordinates of the center of browser's window
var centerX, centerY;
    if( self.innerHeight ) {
	centerX = self.innerWidth;
	centerY = self.innerHeight;
    } else if( document.documentElement && document.documentElement.clientHeight ) {
	centerX = document.documentElement.clientWidth;
	centerY = document.documentElement.clientHeight;
    } else if( document.body ) {
	centerX = document.body.clientWidth;
	centerY = document.body.clientHeight;
    }
// Xwidth is the width of the div, Yheight is the height of the  div passed as arguments to the function:
var leftoffset = scrolledX + (centerX - Xwidth) / 2;
var topoffset = scrolledY + (centerY - Yheight) / 2;
var pos = new Array(leftoffset,topoffset);
    return pos;
} 
function showAlert(objId){
      if (coordsY == 0)
          coordsY = 600;
      var hafClH = Math.floor(document.body.clientHeight/2);
      var fix = (coordsY+100) - hafClH;
      var showDiv_obj = document.getElementById(objId);
      showDiv_obj.style.top = (document.body.scrollTop + coordsY) - fix;
      showDiv_obj.visible = true; 
      showDiv_obj.style.display = 'block'; 
}
function showOpasDiv(divId){ 
 var divObj = document.getElementById(divId);
	try  {
	    if(divObj.style.height != 0){
	    divObj.style.height =  document.getElementById("wrapper").offsetHeight + "px"; 
	    }else{
		showDiv(divId);
	    }
	  }catch(err){
	    divObj.style.height =  document.getElementById("mainDiv").offsetHeight + "px"; 
	  }
     divObj.style.display = 'block'; 
}  
function cropString(str, max){
    var newStr = str;
    if (str != null) {
        if(newStr.length > max)
            newStr = newStr.substr(0,max) + "...";
    }
    return newStr;
}
function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit){
      field.value = field.value.substring(0, maxlimit);
    }else{
      document.getElementById(countfield).innerHTML = maxlimit - field.value.length;
      }
}
function fixPNG(element){
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)){
		var src;
                src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
                 if (src){
                    src = src[1];
                    element.runtimeStyle.backgroundImage="none";
                }
		if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	}
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
    if (( version < 7) && (document.body.filters)) {
      for(var i=0; i<document.images.length; i++){
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }  
}
var buttonColor = "";
var buttonText = "";
var IE=window.external&&(navigator.platform=="Win32"||(window.ScriptEngine&&ScriptEngine().indexOf("InScript")+1));
var FF=(navigator.userAgent.toLowerCase().indexOf("firefox")+1)?true:false;
var OP=window.opera&&window.print;
var NS=window.netscape&&!OP;
function copyToClipboard(content, infDivId, buttObj) {
        if(IE&&!FF){
                if(!window.clipboardData.setData("Text",content)){
		    openInfo('infoDiv','Text was not copied','Text was not copied to clipboard!', '');
                    return false;
                    }
                else{
		    if(buttObj){
			buttonColor = buttObj.style.color;
			buttObj.style.color = "#fff799";
			buttonText = buttObj.innerHTML;
			buttObj.innerHTML = "Copied!";
			setTimeout(function(){buttObj.style.color = buttonColor; buttObj.innerHTML = buttonText;}, 3000);
		    }else{
			openInfo('infoDiv','Text was copied','Text successfully copied to clipboard!', '');
		    }
                    return true;
                    }
        } else {
                try { 
                        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
                } 
                catch (e) { 
                        //alert("Text was not copied. This is probably due to a security restriction on your browser that prevented the page from accessing your clipboard. Your best bet would be to select the text and copy it the regular way (Ctrl+C, for instance)");
			openInfo('infoDiv','Text was not copied ','This is probably due to a security restriction on your browser that prevented the page from accessing your clipboard. Your best bet would be to select the text and copy it the regular way (Ctrl+C, for instance)', '');
	                return false;
                }
                try{
                    var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard)
                        }catch(e){return false}
                try{
                    var transferable=Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable)
                        }catch(e){return false}

                if (clipboard && transferable) { 
                        // type of transferable data   
                        transferable.addDataFlavor("text/unicode"); 
                        var textObj = new Object(); 
                        var textObj = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 
                        if (textObj) { 
                                textObj.data = content; 
                                // We pack data into the container 
                                transferable.setTransferData("text/unicode", textObj, content.length*2); 
                                var clipid=Components.interfaces.nsIClipboard; 
                                clipboard.setData(transferable,null,clipid.kGlobalClipboard); 
				if(buttObj){
				    buttonColor = buttObj.style.color;
				    buttObj.style.color = "#fff799";
				    buttonText = buttObj.innerHTML;
				    buttObj.innerHTML = "Copied!";
				    setTimeout(function(){buttObj.style.color = buttonColor; buttObj.innerHTML = buttonText;}, 3000);
				}else{
				    openInfo('infoDiv','Text was copied ','Text successfully copied to clipboard!', '');
				}
                                return true;
                        } 
                }else{
                //alert("Text was not copied. This is probably due to a security restriction on your browser that prevented the page from accessing your clipboard. Your best bet would be to select the text and copy it the regular way (Ctrl+C, for instance)");}
		openInfo('infoDiv','Text was not copied ','This is probably due to a security restriction on your browser that prevented the page from accessing your clipboard. Your best bet would be to select the text and copy it the regular way (Ctrl+C, for instance)', '');
                return false;
		}
        }
}

function showInform(text,divId){
    var informDiv = document.getElementById(divId);
        informDiv.innerHTML = text;
}
function checkValidMessageChars(str){
    //var iChars = "*|/\"<>[]{}`;()&$#%";
      var iChars = "*|\<>[]{}&$#%";
    return specialCheckValidChars (str,iChars)
}
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = 'images/grayStyle/unchecked.gif';
var imgTrue = 'images/grayStyle/checked.gif';
var buttonId;
function replaceChecks() {
        //get all the input fields on the page
        inputs = document.getElementsByTagName('input');

        //cycle trough the input fields
        for(var i=0; i < inputs.length; i++) {
            //check if the input is a checkbox
            // Making sure the replace will only happen once
            if(inputs[i].getAttribute('type') == 'checkbox' && inputs[i].style.display != 'none') {
                //create a new image
                var img = document.createElement('img');

                //check if the checkbox is checked
                if(inputs[i].checked) {
                    img.src = imgTrue;
                } else {
                    img.src = imgFalse;
                }
                //set image ID and onclick action
                img.id = 'checkImage'+i;
           
                //set image 
                img.onclick = new Function('checkChange('+i+');enableSubmit()');
                
                //place image in front of the checkbox
                inputs[i].parentNode.insertBefore(img, inputs[i]);
                //hide the checkbox
                inputs[i].style.display='none';
            }
        }
    }
  //change the checkbox status and the replacement image
    function checkChange(i) {
        if(inputs[i].checked) {
            inputs[i].checked = '';
            document.getElementById('checkImage'+i).src=imgFalse;
        } else {
            inputs[i].checked = 'checked';
            document.getElementById('checkImage'+i).src=imgTrue;
        }
    }
var submitButtonId = "submitBut";
var submitButtonSize = "75X26";
function disableSubmit(){ 
         var butObj = document.getElementById(submitButtonId);
             butObj.className = "disableCol";
	 var but2Obj = document.getElementById('canBut');
             but2Obj.className = "disableCol";
           }
function enableSubmit(){ 
        if(document.getElementById(submitButtonId)){
         var butObj = document.getElementById(submitButtonId);
             butObj.className = "";
             butObj.onclick =  function(){if (document.forms.editProfile.onsubmit()) document.forms.editProfile.submit()};
             }
	 if(document.getElementById('canBut')){
         var but2Obj = document.getElementById('canBut');
             but2Obj.className = "";
             }
        }   
function sendImgPlase(arrIndex){
  var coordParam = parseInt(arrIndex) + 1;
  return coordParam;
}
function showDimByHeight(divId, blockId){ 
 var divObj = document.getElementById(divId);
if(document.getElementById(blockId)){
 var blockObj = document.getElementById(blockId);
     divObj.style.height =  (blockObj.offsetHeight + 10) + "px"; 
}
     divObj.style.display = 'block'; 
} 
function isLoginPopUp(url, userLoggedInP) {
    if (userLoggedInP == 'true') {
        window.location.href = url;
    } else { 
       document.getElementById("loginDiv").innerHTML = strLogDiv;
       openLoginDiv();
       document.loginForm.calledFromPage.value = url;
       document.loginForm.username.focus();
    }
}
function openLoginDiv(){
   hideDiv('signUpDiv');
   hideDiv('forgotDiv');
   showDimByHeight('dimDiv', 'mainTab');
   //showDiv('dimDiv');
   showDiv('loginDiv');
   updateUserNameWithCookie();
}
function closeLogin(){
    hideDiv('loginDiv');
    hideDiv('dimDiv');
}
function openSignUp(url){
    document.getElementById("signUpDiv").innerHTML = setSignUpDivHtml();
    closeLogin();
    confirm = false;
    showDiv('signUpDiv');
    showDiv('dimDiv');
    document.signUpForm.username.focus();
    replaceChecks();
    if (url)
        document.signUpForm.calledFromPage.value = url;
}
function closeSignUp(){
    hideDiv('dimDiv');
    hideDiv('signUpDiv');
}
function openForgotPass(){
    document.getElementById("forgotDiv").innerHTML = strForgotDiv;
    hideDiv('loginDiv');
    showDiv('forgotDiv');
    document.forgotForm.username.focus();
}
function closeForgotPass(){
    hideDiv('dimDiv');
    hideDiv('forgotDiv');
}

function closeProcessWin(){
    //hideDiv('dimDiv');
    document.getElementById('dimDiv').style.zIndex="1100"; 
    hideDiv('procesDiv');
}

function openEditInfo(){
    putOnChangeEv();
    showDiv('addPersonalInfo');
    hideDiv('userData');
}
function changeBGImage(objId, styleName){ 
   objId.className = styleName;
}
 var iChars = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm_-+@.";
 var uChars = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm$@";
 function sLoginForm() {
        var formObj = document.loginForm;
        username = formObj.username.value;
        password = formObj.password.value;
        
        errDiv = document.getElementById("errDiv");

        if (username == ""){
           errDiv.innerHTML = "Please type username !"
           formObj.username.focus();
           return false;
	}else{
	     for (var i = 0; i<username.length; i++) {
                if (iChars.indexOf(username.charAt(i)) == -1){
		    errDiv.innerHTML = "Your username contains invalid characters."
		    formObj.username.focus();
		    return false;
                }
            }
        }
	if(password == ""){
            errDiv.innerHTML = "Please type password !"
            formObj.password.focus();
            return false;
        }else{
	     for (var i = 0; i<password.length; i++) {
                if (uChars.indexOf(password.charAt(i)) == -1){
		    errDiv.innerHTML = "Your username contains invalid characters."
		    formObj.password.focus();
		    return false;
                }
            }
        }
	checkUserCred(username, password, errDiv); 
    }

    function checkUserCred(username, password, errDiv) {
        if (errDiv != null)
            errDiv.innerHTML = "Please wait...";
        var propertiesList = new Array();
        propertiesList["password"] = password;
        propertiesListXml = createPropertyList(propertiesList, "userProperties");
        // Make sure to ignore case
        username = username.toLowerCase();
        password = password.toLowerCase();
        // Get user properties
        getUserProperties();
    }

    function getPartnerProperties() {
        var propertyList = "";
        tempNextFunc = "partnerPropUse";
        getPartnerPropApi(propertyList);
    }  
    function getUserProperties(){
        var propertyList = "";
        tempNextFunc = "callLoginUser";
        getUserPropApi(propertyList, username);
    }            
    function callLoginUser(puserId){
        userId = puserId
        // Make sure the user can login
        apiFunction = "setLogininSession(false)";
        doApiFunctionWPass(partner, application);
    }            

    function callRegisterUser() {
         registerUserApi(username, age, propertiesListXml);
    }

    function signUpForm() {
        username = document.signUpForm.username.value;
        password = document.signUpForm.password.value;
        signUpEmail = document.signUpForm.signUpEmail.value;
        allowUpdates = document.signUpForm.allowUpdates.checked ? 'true' : 'false';
        var year = parseInt(document.signUpForm.dateofbirth_year.value);
        var month = parseInt(document.signUpForm.dateofbirth_month.value) - 1;
        var day = parseInt(document.signUpForm.dateofbirth_day.value);
        birthdate = getBirthDate(day, month, year);
        age = getAge(day, month, year);
        
        errDiv = document.getElementById("regErrDiv");
        errDiv.innerHTML = "Please wait...";
        var propertiesList = new Array();
        propertiesList["password"] = password;
        propertiesList["email"] = signUpEmail;
        propertiesList["allowUpdates"] = allowUpdates;
        propertiesList["birthdate"] = birthdate;
        propertiesListXml = createPropertyList(propertiesList, "userProperties");
        // Make sure to ignore case
        username = username.toLowerCase();
        password = password.toLowerCase();
        // Get user properties
        callRegisterUser();
        pageTracker._setVar('registered');
    }

    var postLoginPage = "gizmozLogin.jsp";
    function setLogininSession(defaultUsr) {
        // login was successful
        if (defaultUsr) {
            //data += "&defaultUsr=true";
            //self.setLogininDefSessionResponse = setLogininDefSessionResponse;
            //postUrlXMLResponse(url, data, self.setLogininDefSessionResponse);
            execFunction();
        } else {
            var url = postLoginPage;
            var data = "partner=" + partner + 
              "&username=" + username + 
              "&userIden=" + userId;
            if (apiToken != "")
                data += "&apiToken=" + apiToken;
            data += "&password=" + password;
            confirm = false;
            self.setLogininSessionResponse = setLogininSessionResponse;
            postUrlXMLResponse(url, data, self.setLogininSessionResponse);
        }
    }
   
    function setLogininSessionResponse(xmlHttpRequest) {
        var returnCodeStr = getNodeValue(xmlHttpRequest.responseXML, "return_code");
        if (returnCodeStr == 0) {
            //var userId = getNodeValue(xmlHttpRequest.responseXML, "userId");
            //var email = getNodeValue(xmlHttpRequest.responseXML, "email");
            // The login was successful
            if (errDiv) {
                errDiv.innerHTML = "Logged in successfully!";
            }
	    if(document.loginForm) {
		window.location.href = document.loginForm.calledFromPage.value;
	    } else if (document.signUpForm) {
		window.location.href = document.signUpForm.calledFromPage.value;
	    } else if (calledFromPage) {
                window.location.href = calledFromPage;
            }
            confirm = true;
        } else {
            var err = getNodeValue(xmlHttpRequest.responseXML, "error");
            redirectError(err);
        }      
    }  
    
    function setLogininDefSessionResponse(xmlHttpRequest) {
        var returnCodeStr = getNodeValue(xmlHttpRequest.responseXML, "return_code");
        if (returnCodeStr == 0) {
            execFunction();
        } else {
            var err = getNodeValue(xmlHttpRequest.responseXML, "error");
            redirectError(err);
        }      
    }  

    function redirectError(errorMsg) {
        if (errorMsg) {
            errorMsg = errorMsg.replace(/%20/g," ");
        }
        //alert(errorMsg);
        errDiv.innerHTML = errorMsg;
    }
    
    function addRegisterDiv() {
        showDiv('registerKeyTab');
       }
    
    function forgotForm() {
        errDiv = document.getElementById("forgot_errDiv");
        errDiv.innerHTML = "Please wait...";
        username = document.forgotForm.username.value;
        forgotPassApi(username);
    }
    function checkForgot(formObj) {
        if(formObj.username.value == null || formObj.username.value == ""){
	    document.getElementById("forgot_errDiv").innerHTML = "Please type username !";
            formObj.username.focus();
            return false;
        }
       return true;  
    }
function calImgResize(imgObj, maxWidth, maxHeight){
	var ret = false; 
	var height = (imgObj.height == 0) ? maxHeight : imgObj.height;
	var width = (imgObj.width == 0) ? maxWidth : imgObj.width;

	var sHeight = height;
	var sWidth = width;
        var ra  = maxWidth/maxHeight;
    if(ra == 1){
        var s = maxWidth/(width * ra);
    }else{
	var s = maxWidth/(height * ra); 
    }
            sWidth =  Math.floor(width * s);
	    sHeight = Math.floor(height * s);
            imgObj.width = sWidth;
            imgObj.height = sHeight;
            imgObj.style.width = sWidth +'px';
            imgObj.style.height = sHeight +'px';
    if(maxHeight > imgObj.height)
	    imgObj.style.marginTop = Math.floor((maxHeight - imgObj.height)/2)+ 'px';
	       // alert(imgObj.style.top+' = ('+maxHeight+ ' - ' +imgObj.height+')/2');
	    imgObj.style.visibility = "visible";
    return ret;
}
function bannerHref(link,target,gaHit){
    if (link != "") {
        if(target == '_blank') { 
            window.open(link);
        }else{
            window.location.href = link; 
        }
        pageTracker._trackPageview(gaHit); 
    }
}
/* New*/
var creatorNum = 0;
 function myObj(){
                this.id =  0;
                this.img = "";
                this.imgUrl = "";
                this.title = "";
                this.creator = "";
                this.createdDay = "";
                this.addedDay = "";
                this.remixed = 0;
                this.duration = 0;
                this.rating = 0;
                this.creatorJoined = 0;
                this.totalVideos = 0;
                this.views = 0;
                this.butUrl = "";
                this.trashEvent = "";
                this.popTempStar = 0; 
                this.tags = ""; 
              }
           
            function doDivSketch(myEntry,gallType){
                var divsArrForGallery = new Array(); 
                for( var entryVal in myEntry ) {
                    var divCell = document.createElement("div");
                    divCell.className = gallType;
                    for( var entry in myEntry[entryVal]) {                  
                        switch(entry) {
                        
                         case 'id':
                           id = myEntry[entryVal][entry];
                           divCell.id = id;
                          break;
  
                         case 'title':
                            var div = document.createElement("div");
                            div.className = gallType + "_title";

                            var titleHref = myEntry[entryVal]['imgUrl'];
                                if(titleHref != "" && titleHref != null) { 
                                    div.style.cursor = "pointer";
                                    div.onclick = new Function("doOnclickUrl(\""+ titleHref + "\")");
                            }

			    if(gallType =="myStuffVideos" || gallType =="myHeads"){
				hoverTopDiv.appendChild(div);
			    }else{
				divCell.appendChild(div);
			    }
                            var cutNum;
                                if(gallType == "myHeads"){
                                    cutNum = 8;
                                }else{
                                    cutNum = 16;
                                }
                            span = document.createElement("span");
                            div.appendChild(span);
                            var titleText = document.createTextNode(cropString(myEntry[entryVal][entry],cutNum));
                            span.appendChild(titleText);
                         break;
                           
                         case 'creator':
                             var creatorName = myEntry[entryVal][entry];
                             if(creatorName != "" && creatorName != null){
                                 var div = document.createElement("div");
                                 div.className = gallType + "_creator";
                                 div.style.cursor = "pointer";
                                 div.onclick = new Function("doOnclick_creator(\""+ creatorName + "\")");
                                 divCell.appendChild(div);
                                 span = document.createElement("span");
                                 div.appendChild(span);
                                 var titleText = document.createTextNode(cropString(creatorName,14));
                                 span.appendChild(titleText);
                            }
                           break; 

                         case 'img':     					   
                            var imgSrc = myEntry[entryVal][entry];
                             if(imgSrc != "" && imgSrc != null){
                               var div = document.createElement("div");
                                div.className = gallType + "_img";
                                img = document.createElement("img");

				if(gallType =="myStuffVideos" || gallType =="myHeads"){ /* For resize */

				    var maxW= (gallType != "myHeads") ? 166 : 128;
                                    var maxH= (gallType != "myHeads") ? 90 : 128;

				     if(imgSrc.indexOf("default")==-1){
                                        img.style.visibility = "hidden";
                                        img.onload = new Function("calImgResize(this, \""+maxW+"\", \""+maxH+"\")");
                                     }
                                  if(imgSrc.indexOf("image/default")>-1)
                                       div.className = gallType + "_img_none";

				pageNum = window.location.hash.substr(1);
                                 if (!pageNum) pageNum=1;
				    //if(entryVal == 0 && pageNum == 1){
					//headAccess = divCell.id;
				    //}
				 var hoverBottomDiv = document.createElement("div"); /* for myStuffVideos gallery RollOver Div */
				     hoverBottomDiv.className =  gallType + "_hoverBottomDiv";
				     divCell.appendChild(hoverBottomDiv);
				     if(gallType =="myHeads"){
					var radioButDiv = document.createElement("div");
					    radioButDiv.className = gallType +"_radioButDiv";
					var radioBut = document.createElement("input");
					    radioBut.type = "radio";
					    radioBut.name = "defaultHead";
					    radioBut.value = divCell.id;
					    radioBut.id = "defaultHead" + divCell.id;
					    radioBut.onclick = function(){
						this.checked = true;
						changeDefaultHead(this.value);
					    }
					var label = document.createElement("label");
					    label.setAttribute("for",divCell.id);
					var labeltext = document.createTextNode("Profile character");
					    label.appendChild(labeltext);
					    radioButDiv.appendChild(radioBut);
					    radioButDiv.appendChild(label);
					    hoverBottomDiv.appendChild(radioButDiv);
				     }
				 
				 var hoverTopDiv = document.createElement("div");
				     hoverTopDiv.className =  gallType + "_hoverTopDiv";   
				     divCell.appendChild(hoverTopDiv);
				     divCell.onmouseover = function() {
					this.childNodes[0].style.display = 'block';
					this.childNodes[1].style.display = 'block';
					this.className = gallType+"_rollOver"
				     }
				     divCell.onmouseout = function() {
					this.childNodes[0].style.display = 'none';
					this.childNodes[1].style.display = 'none';
					this.className = gallType;
				     }
				}
                              if(gallType == "videos" || gallType =="videosHP" || gallType =="popularTempHP" || gallType =="youTubeHP" || gallType == "myHeads_old"){ /* For resize */
			                                      
                                var maxW= (gallType != "myHeads_old") ? 187 : 93;
                                var maxH= (gallType != "myHeads_old") ? 105 : 93;

                                   if(imgSrc.indexOf("image/default")==-1){
                                        img.style.visibility = "hidden";
                                        img.onload = new Function("calImgResize(this, \""+maxW+"\", \""+maxH+"\")");
                                    }
                                    if(imgSrc.indexOf("image/default")>-1)
                                       div.className = gallType + "_img_none";
 
                              }      
                              img.src = imgSrc;  

                                div.appendChild(img);
                                if(gallType == "topCreators"){
                                    creatorNum = creatorNum+1;
                                    var placeDiv = document.createElement("div");
                                        placeDiv.className = gallType + "_placeDiv_"+creatorNum;
                                    var placeImg = document.createElement("img");
                                        placeImg.src = "images/" + creatorNum + "_place.png";
                                        placeDiv.appendChild(placeImg);
                                        divCell.appendChild(placeDiv);
                                }
                                divCell.appendChild(div);
                            }
                           break; 

                         case 'imgUrl':
                            var imgHref = myEntry[entryVal][entry];
                            var gaString = myEntry[entryVal]['gaHitString'];
                            if(gaString){
                              gaString = gaString.replace("{hitPlace}","picture");
                              gaString = gaString.replace("{index}",sendImgPlase(entryVal));
			      gaString = gaString.replace("{hitVal}","view");
                            }
                            if(imgHref != "" && imgHref != null) { 
                                img.style.cursor = "pointer";
                                img.onclick = new Function("doOnclickUrl(\""+ imgHref + "\",\""+ gaString + "\")");

				    if(gallType =="myStuffVideos" || gallType =="myHeads"){
					    gaString = gaString.replace("picture","button");
					var div = document.createElement("div");
					    div.className = gallType + "_view";
					    div.onmouseover = function(){this.className = gallType + "_view_rollover";};
					    div.onmouseout = function(){this.className = gallType + "_view";};
					    div.onclick = new Function("doOnclickUrl(\""+ imgHref + "\",\""+ gaString + "\")");

					var text = document.createTextNode("View");		    
					    div.appendChild(text);
					    hoverBottomDiv.appendChild(div);
				    }
                            }
                          break; 

                         case 'creatorJoined':
                            var joinedMonth = cropString(myEntry[entryVal][entry],9);
                            if(joinedMonth!= "" && joinedMonth != null &&joinedMonth != 0){
                                var div = document.createElement("div");
                                    div.className = gallType + "_creatorJoined";
                                    divCell.appendChild(div);
                                var textS = document.createTextNode("Joined: ");     
                                    div.appendChild(textS);
                                var span = document.createElement("span");
                                    div.appendChild(span);
                                var text = document.createTextNode(joinedMonth);
                                    span.appendChild(text);
                             }
                           break; 
                        
                         case 'creatorImg':
                            var creatorImgSrc = myEntry[entryVal][entry];
                             if(creatorImgSrc != "" && imgSrc != null){
                               var div = document.createElement("div");
                                div.className = gallType + "_creator_img";
                                 var imgC = document.createElement("img");
                                 imgC.src = creatorImgSrc;
                                div.appendChild(imgC);
                                divCell.appendChild(div);
                              }
                           break; 

                        case 'description':
                            var description = myEntry[entryVal][entry]; //cropString(myEntry[entryVal][entry],9);
                            var div = document.createElement("div");
                                div.className = gallType + "_description";
                                divCell.appendChild(div);
                            var text = document.createTextNode(description);
                                div.appendChild(text);
                           break;

                         case 'totalVideos':
                            var videosNum = cropString(myEntry[entryVal][entry],5);
                             if(videosNum != "" && videosNum != null) { 
                                var div = document.createElement("div");
                                    div.className = gallType + "_totalVideos";
                                    divCell.appendChild(div);

                                var text = document.createTextNode("Videos: " + videosNum );
                                    div.appendChild(text);
                                }
                           break; 

                         case 'createdDay':
                             var creatDay = myEntry[entryVal][entry];
                             if(creatDay!= "" && creatDay != null && creatDay.indexOf('undefined') == -1 ){
                                var div = document.createElement("div");
                                div.className = gallType + "_createdDay";

				if(gallType =="myStuffVideos" || gallType =="myHeads"){
				    hoverTopDiv.appendChild(div);
				}else{
				    divCell.appendChild(div);
				    var titleText = document.createTextNode("Created: ");
					div.appendChild(titleText);
				}
                                span = document.createElement("span");
                                div.appendChild(span);
                                var text = document.createTextNode(cropString(creatDay,8));
                                span.appendChild(text);
                            }
                           break; 
                         
                         case 'timeAgo':
                             var timeAgo = myEntry[entryVal][entry];
                             if (timeAgo!= "" && timeAgo != null && timeAgo.indexOf('undefined') == -1 ){
                                var div = document.createElement("div");
                                div.className = gallType + "_timeAgo";
                                divCell.appendChild(div);
                                //var titleText = document.createTextNode("");
                                //div.appendChild(titleText);

                                span = document.createElement("span");
                                div.appendChild(span);
                                var text = document.createTextNode("(" + timeAgo + ")");
                                span.appendChild(text);
                            }
                           break; 

                         case 'addedDay':
                          var addDayNum = myEntry[entryVal][entry];
                          if(addDayNum != "" && addDayNum != null) { 
                            var div = document.createElement("div");
                            div.className = gallType + "_addedDay";
                            divCell.appendChild(div);
                            var titleText = document.createTextNode("Added: ");
                            div.appendChild(titleText);
                            
                            span = document.createElement("span");
                            div.appendChild(span);
                            var text = document.createTextNode(cropString(addDayNum,8));
                            span.appendChild(text);
                           } 
                           break;
                           
                         case 'remixed':
                            if (myEntry[entryVal][entry]) {
                                var div = document.createElement("div");
                                div.className = gallType + "_remixed";
                                divCell.appendChild(div);
                                var titleText = document.createTextNode("Remixed: ");
                                div.appendChild(titleText);

                                span = document.createElement("span");
                                div.appendChild(span);
                                var text = document.createTextNode(cropString(myEntry[entryVal][entry],8));
                                span.appendChild(text);
                            }
                           break; 

                          case 'views':
                            var div = document.createElement("div");
                            div.className = gallType + "_views";
                            divCell.appendChild(div);
                            var titleText = document.createTextNode("Views: ");
                            div.appendChild(titleText);
                            
                            span = document.createElement("span");
                            div.appendChild(span);
                            var text = document.createTextNode(cropString(myEntry[entryVal][entry],6));
                            span.appendChild(text);
                          break;   

                         case 'rating':
                            var ratingNum = myEntry[entryVal][entry];
                            if(ratingNum != " " && ratingNum != null) { 
                                var div = document.createElement("div");
                                div.className = gallType + "_rating";
                                divCell.appendChild(div);
                                div.appendChild(paintStars(ratingNum, '', '', div.id));
                            }
                         break;   
   
                        case 'butUrl':
                            var linkUrl = myEntry[entryVal][entry];
                            var gaString = myEntry[entryVal]['gaHitString'];
                                if(gaString){
                                  gaString = gaString.replace("{hitPlace}","button");
                                  gaString = gaString.replace("{index}",sendImgPlase(entryVal));
				  gaString = gaString.replace("{hitVal}","remix");
                                }
                             if(linkUrl != "" && linkUrl != null){
                                var div = document.createElement("div");
                                    div.className = gallType + "_button";
				    div.onmouseover = function(){this.className = gallType + "_button_rollover";};
				    div.onmouseout = function(){this.className = gallType + "_button";};
				    div.onclick = new Function("doOnclickUrl(\""+ linkUrl + "\",\""+ gaString + "\")");
                                    var btnText = document.createTextNode("Edit");		    
                                    div.appendChild(btnText);

				    if(gallType =="myStuffVideos" || gallType =="myHeads"){
					hoverBottomDiv.appendChild(div);
				    }else{
					divCell.appendChild(div);
				    }
                           } 
                           break;   

                        case 'trashEvent':
                            var deleteFuncName = myEntry[entryVal][entry];
                            if(deleteFuncName != "" && deleteFuncName != null){
                              var div = document.createElement("div");
                                    div.className = gallType + "_trashEvent";
				    div.onclick =  new Function("headName=\""+myEntry[entryVal]['title']+"\";eval("+deleteFuncName+");");
                                    /*div.onmouseover = function(){this.className = gallType + "_trashEvent_rollover";};
                                    div.onmouseout = function(){this.className = gallType + "_trashEvent";};
                                    div.onmousedown = function(){this.className = gallType + "_trashEvent_press";};
                                    div.onmouseup = function(){this.className = gallType + "_trashEvent_rollover";};
                                    btnSpan = document.createElement("span");
                                    var btnText = document.createTextNode("Delete");
                                    btnSpan.appendChild(btnText);
                                    div.appendChild(btnSpan);*/

				    if(gallType =="myStuffVideos" || gallType =="myHeads"){
					hoverBottomDiv.appendChild(div);
				    }else{
					divCell.appendChild(div);
				    }
                             }
                           break;  
                       
                       case 'abuseEvent':
                            var abuseFuncName = myEntry[entryVal][entry];
                            if(abuseFuncName != "" && abuseFuncName != null){
                              var div = document.createElement("div");
                                  div.className = gallType + "_abuseEvent";
                                  div.onclick =  new Function("eval("+abuseFuncName+");this.onclick='';this.className='"+gallType + "_abuseEvent_dis';");
                                  divCell.appendChild(div);
                             }
                           break;  

                        case 'editItem':
                            var editFuncName = myEntry[entryVal][entry];
			    var gaString = myEntry[entryVal]['gaHitString'];
			    if(gaString){
			      gaString = gaString.replace("{hitPlace}","button");
			      gaString = gaString.replace("{hitVal}","info");
			    }
                            if (editFuncName != "" && editFuncName != null){
                                var div = document.createElement("div");
                                    div.className = gallType + "_editItem";
				    div.onmouseover = function(){this.className = gallType + "_editItem_rollover";};
				    div.onmouseout = function(){this.className = gallType + "_editItem";};
                                    div.onclick =  new Function("eval("+editFuncName+");pageTracker._trackPageview('"+gaString+"')");
				var btnText = document.createTextNode("Info");
                                    div.appendChild(btnText);
				if(gallType =="myStuffVideos" || gallType =="myHeads"){
				    hoverBottomDiv.appendChild(div);
				}else{
				    divCell.appendChild(div);
				}
                             }
                           break;  

                        case 'printItem':
                            var printFuncName = myEntry[entryVal][entry];
                            var gaString = myEntry[entryVal]['gaHitString'];
                            if (printFuncName != "" && printFuncName != null){
                                var div = document.createElement("div");
                                div.className = gallType + "_printItem";
                                div.onclick =  new Function("eval("+printFuncName+");pageTracker._trackPageview('"+gaString+"')");
                                divCell.appendChild(div);
                            }
                            break;  

                        case 'authorization':
                            var authoParam = myEntry[entryVal][entry];
                            if (authoParam != "" && authoParam != null){
                              var div = document.createElement("div");
                                  div.className = gallType + "_authoParam_" + authoParam;
                                  //div.onclick =  new Function("eval("++");");
				   if(gallType =="myStuffVideos" || gallType =="myHeads"){
					hoverBottomDiv.appendChild(div);
				    }else{
					divCell.appendChild(div);
				    }
                             }
                           break;  

                          case 'printNgift':
                            var aprintNgiftParam = myEntry[entryVal][entry];
                            if (aprintNgiftParam != "" && aprintNgiftParam != null){
                              var div = document.createElement("div");
                                  div.className = gallType + "_aprintNgiftParam";
                                  div.onclick =  new Function("doOnclickUrl()");
                                  divCell.appendChild(div);
                             }
                           break;  

                       case 'popTempStar':
                            if(myEntry[entryVal][entry] != "" && myEntry[entryVal][entry] != null) { 
                                var div = document.createElement("div");
                                    div.className = gallType + "_popTempStar";
                                    divCell.appendChild(div);

                                var topNumSpan = document.createElement("span");
                                    //topNumSpan.className = gallType + "_topNum";

                                var topNumText = document.createTextNode(cropString(myEntry[entryVal][entry],4));
                                    topNumSpan.appendChild(topNumText);
                                    div.appendChild(topNumSpan);

                                var text = document.createTextNode("Remixes");
                                div.appendChild(text);
                            }
                           break;
                           
                          case false:
                           //if myVar is false (or 1 or 'sample', see the next paragraph)
                            //this is executed
                          default:
                            //if myVar does not satisfy any case, (or if it is
                            //1 or 'sample' or false, see the next paragraph)
                            //this is executed
                        }
                    }
                    divsArrForGallery[entryVal] = divCell;                  
                }
                return divsArrForGallery;
            }
            var ratingWords = new Array("","Poor","Not so good","Ok", "Good", "Awesome!"); 
            function paintStars(rating, editOption, itemId, parentDivId) {
                var table = document.createElement("table");
                table.cellSpacing = 0;
                table.cellPadding = 0;
                tr = table.insertRow(-1);
                var divName = parentDivId;
                var ratedCookie = readCookie(itemId) ? true : false;
                if (editOption == "edit") {
                    if (!ratedCookie) {
                        document.getElementById(parentDivId).parentNode.onmouseout = 
                            new Function("lightStars('"+rating+"','"+divName+"')");
                    }
                    var ratingSpan = document.getElementById("raitingWords");
                    if(!isNaN(rating)){
                        ratingSpan.innerHTML = ratingWords[rating];
                    }
                }
                for (var i=1; i <= 5; i++) { 
                    td = tr.insertCell(-1);
                    var ratingImg = document.createElement("img");
                    ratingImg.id = parentDivId + "_ratingStar"+i;
                    // Only if this item wasn't rated before
                    if (editOption == "edit" && !ratedCookie) {
                        ratingImg.style.cursor = "pointer";
                        ratingImg.onclick = new Function("rateItem(\""+itemId+"\",\""+i+"\")");
                        ratingImg.onmouseover = new Function("lightStars('"+i+"','"+divName+"')");
                    }
                    if (i <= rating) {
                        ratingImg.src = "images/star_F.gif";
                    } else { 
                        ratingImg.src = "images/star_N.gif";
                    }
                    td.appendChild(ratingImg);              
                } 
                return table;
            }
            // Use this for users that already rated
            function disableStars(parentDivId) {
                var prefixName = parentDivId + "_ratingStar";
                for (var i=1; i <= 5; i++){ 
                    var starElem = document.getElementById(prefixName + i);
                    starElem.style.cursor = "default";
                    starElem.onclick = "";
                    starElem.onmouseover = "";
                }
            }
            // Use this for users that already rated
            function lightStars(starNum, parentDivId) {
                var prefixName = parentDivId + "_ratingStar";
                var ratingSpan = document.getElementById("raitingWords");          
                // Turn off 
                for (var i=5; i > starNum; i--){ 
                    var starElem = document.getElementById(prefixName + i);
                    starElem.src = "images/star_N.gif";
                    ratingSpan.innerHTML = ratingWords[i];
                }
                // Light on
                for (var i=1; i <= starNum; i++){ 
                    var starElem = document.getElementById(prefixName + i);
                    starElem.src = "images/star_F.gif";
                    ratingSpan.innerHTML = ratingWords[i];
                }
            }
            function doOnclick(linkUrl,id){
                window.location.href = linkUrl + "?partner=" + partner + "&scene=" + id;
            }
            var emptyGalMessage = "";
            function clearGallery(gallDivId){
	       if(emptyGalMessage == "") emptyGalMessage = "Nothing to display.";
               var divObj = document.getElementById(gallDivId); 
               divObj.innerHTML = '<div class="regTxt"><center> <br><br>' + emptyGalMessage + '<br><br> </center></div>';
            }
            function doOnclick_creator(creator){
                window.location.href = "myStuff.jsp?partner=" + partner + "&requestUsername=" + creator;
            }

            function doGalleryTable(dataArr, pageNum, quantityToShow, totalItems, pagingType, col, containerId, pagingFunc, moreUrl){
                if (dataArr == "" || dataArr == null) return;
                var numOfTotalPage =  Math.ceil(totalItems/quantityToShow);
                var countTD = 0;
                var countTR; 
                var table;
                var gallDataLength = totalItems;
                var galleryDiv = document.getElementById(containerId);
                galleryDiv.innerHTML = "";
                table = document.createElement("table");
                table.cellSpacing = (containerId != "gallery_wrap") ? 0 : 10;
		table.cellSpacing = 0;
                table.cellPadding = 0;
                table.border= 0;
                table.id = "galTab_" + containerId;
                tr = table.insertRow(-1);// first TR of table
                countTR = 1;
                for (var i = 0; i < quantityToShow; i++){    
                    if (dataArr[i] == null)  break ;

                     if(countTD == col) { 
                        tr = table.insertRow(-1);
                        td.id = "lastTD";
                        countTD = 0;
                        countTR++;
                         if(countTR==quantityToShow/col) {
                            tr.id = "lastTR";
                        }
                    }
                    td = tr.insertCell(-1);
                    if( i == (quantityToShow -1)){
                        td.id = "lastTD";
                        td.colSpan = (col-countTD);
                    } 
                    if( pageNum == numOfTotalPage && i==(gallDataLength%quantityToShow -1)){
                        tr.id = "lastTR";
                        td.id = "lastTD";
                        td.colSpan = (col-countTD); 
                                 if(countTR<(quantityToShow/col)){
                                         for (var r = 0; r < (quantityToShow/col)-countTR; r++){  
                                             tr = table.insertRow(-1);
                                             tr.id = "spaceTR";
                                             var td1 = tr.insertCell(-1);
                                             td1.colSpan = col;
                                         }
                                 }
                    }
                    td.className = "tdTab_" + containerId;
                    td.appendChild(dataArr[i]);
                    countTD++;   
                }
                galleryDiv.appendChild(table);
              //---->> Footer
                var pagingDiv = document.createElement("div"); 
                pagingDiv.className = "pagingDiv";
                
                //---> see more --------> --------> -------->          
                if (pagingType == "more"){
                   var pagingLink = document.createElement("a");
                   pagingLink.setAttribute('href',"javascript:doOnclickUrl(\""+ moreUrl + "\")");
                   pagingDiv.appendChild(pagingLink);
                   var linkText = document.createTextNode("View More >>");
                   pagingLink.appendChild(linkText); 
                }
                //---> pading --------> --------> -------->
                if (pagingType == "paging"){
                    if (gallDataLength > quantityToShow) {
                        var pageViwed = (containerId == "myHeads") ? 2 : 5;
                        var first = (pageNum < pageViwed) ? 1 : (pageNum - pageViwed + 1);
		        var last  = (pageNum > (numOfTotalPage - pageViwed)) ? numOfTotalPage : (pageNum + pageViwed - 1);
                        var arrLeftDiv2 = document.createElement("div");
                            arrLeftDiv2.className = "pagingDiv_arrow_" +((pageNum > pageViwed) ? "unselected" : "selected");
                            pagingDiv.appendChild(arrLeftDiv2);
                        var goToFirst = pagingFunc +"(1);";
                            if(pageNum > pageViwed)
                            arrLeftDiv2.onclick = new Function(goToFirst);
                        var arrLeft2 = document.createTextNode("<<");
                            arrLeftDiv2.appendChild(arrLeft2); 
                        var arrLeftDiv = document.createElement("div");
                            arrLeftDiv.className = "pagingDiv_arrow_" +(((pageNum-1) > 0) ? "unselected" : "selected");
                            pagingDiv.appendChild(arrLeftDiv);
                        var goToLeft = pagingFunc +"("+(pageNum-1).toString()+");";
                            if((pageNum-1) > 0)
                            arrLeftDiv.onclick = new Function(goToLeft);
                        var arrLeft = document.createTextNode("<");
                            arrLeftDiv.appendChild(arrLeft); 
                        for (var p = first; p <= last; p++){ 
                            var pagingLink = document.createElement("div");
                            pagingLink.id = p;
                            pagingLink.className = "pagingDiv_" +((pagingLink.id == pageNum) ? "selected" : "unselected");
                            var goToPageGallery = pagingFunc +"("+p.toString()+");";
                            pagingLink.onclick = new Function(goToPageGallery);
                            var linkText = document.createTextNode(p);
                            pagingLink.appendChild(linkText); 
                            pagingDiv.appendChild(pagingLink);
                        }//end for
                        var arrRightDiv = document.createElement("div");
                            arrRightDiv.className = "pagingDiv_arrow_" +((pageNum < last) ? "unselected" : "selected");
                            pagingDiv.appendChild(arrRightDiv);
                        var goToRight = pagingFunc +"("+(pageNum+1).toString()+");";
                            if(pageNum < last)
                            arrRightDiv.onclick = new Function(goToRight);
                        var arrRight = document.createTextNode(">");
                            arrRightDiv.appendChild(arrRight); 
                        var arrRightDiv2 = document.createElement("div");
                            arrRightDiv2.className = "pagingDiv_arrow_" +((last != numOfTotalPage) ? "unselected" : "selected");
                            pagingDiv.appendChild(arrRightDiv2);
                        var goToLast = pagingFunc +"("+numOfTotalPage.toString()+");";
                            if(last != numOfTotalPage)
                            arrRightDiv2.onclick = new Function(goToLast);
                        var arrRight2 = document.createTextNode(">>");
                            arrRightDiv2.appendChild(arrRight2);   
                    }
                }       
                galleryDiv.appendChild(pagingDiv);
            }

function doStyle(id,styleClass) {
    document.getElementById(id).className = styleClass;
}             
   
function addSpace(str) {
     var s = new String();
     var temp = new Array();
     temp = str.split(',');
     for (var i = 0; i < temp.length; i++) {
        var buffSTR = new String();
            buffSTR = temp[i];
            s += buffSTR +((i != temp.length-1) ? ", " : "");
     }
    return s;
}

function ParseYYYYMMDDtoMMDDYYYY(origDate) {
    var dateStr = origDate.substr(0, 10);
    var dateSplit = dateStr.split("-");
    var newDate = dateSplit[1] + "." + dateSplit[2] + "." + dateSplit[0];
    return newDate;
}

function ParseDDMMMYYYY(origDate) {
    var dateSplit = origDate.split("-");
    return dateSplit;
}

function DDMMYY(origDate) {
    var dateStr = origDate.substr(0, 10);
    var dateSplit = dateStr.split("-");
    var newDate = dateSplit[2] + "." + dateSplit[1] + "." + dateSplit[0].substr(2,2);
    return newDate;
}

function MMMYYYY(origDate) {
    var newDate = (origDate.replace(".","/")).replace(".","/");
    var tempDate = new Date();
    tempDate.setTime(Date.parse(newDate));
    var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var curr_month = tempDate.getMonth();
    var curr_year = tempDate.getFullYear();
    return m_names[curr_month] + ", " + curr_year;
}

function NNAGO(origDate) {
    var currDate = new Date();
    var newTime = currDate.getTime() + currDate.getTimezoneOffset()*60000;
    currDate.setTime(newTime);

    var dateStr = origDate.substr(0, 10);
    var timeStr = origDate.substr(11, 8);
    var dateSplit = dateStr.split("-");
    var newDate = dateSplit[1] + "/" + dateSplit[2] + "/" + dateSplit[0] + " " + timeStr;
    var tempDate = new Date();
    tempDate.setTime(Date.parse(newDate));
    var timeAgo = "";
    var units = "";
    var done = false;
    // Years
    if (currDate.getFullYear() != tempDate.getFullYear()) {
        units = "year";
        done = true;
        timeAgo = currDate.getFullYear()-tempDate.getFullYear();
        if (timeAgo == 1 && (currDate.getMonth() < tempDate.getMonth())) {
            done = false;
        }
    }
    // Months
    if (!done && (currDate.getMonth() != tempDate.getMonth())) {
        units = "month";
        done = true;
        timeAgo = currDate.getMonth()-tempDate.getMonth();
        if (timeAgo < 0)
            timeAgo += 12;
        if (timeAgo == 1 && (currDate.getDate() < tempDate.getDate())) {
            done = false;
        } 
    } 
    // Weeks, days...
    if (!done) {
        var oneSec = 1000;
        var oneMin = 1000*60;
        var oneHour = 1000*60*60;
        var oneDay = 1000*60*60*24;
        var oneWeek = 1000*60*60*24*7;
        var timeDiff = currDate.getTime()-tempDate.getTime();
        timeAgo = Math.round(timeDiff/oneSec);
        if (timeAgo > 59) {
            timeAgo = Math.round(timeDiff/oneMin);
            if (timeAgo > 59) {
                timeAgo = Math.round(timeDiff/oneHour);
                if (timeAgo > 23) {
                    timeAgo = Math.round(timeDiff/oneDay);
                    if (timeAgo > 6) {
                        timeAgo = Math.round(timeDiff/oneWeek);
                        units = "week";
                    } else {
                        units = "day";
                    }
                } else {
                    units = "hour";
                }
            } else {
                units = "minute";
            }
        } else {
            units = "second";
        }
    }
    if (timeAgo > 1)
        units += "s";
    timeAgo += " " + units + " ago";
    return timeAgo;
}

function getArray(arrObj) {
    var resArr = arrObj?arrObj:[];
    if (resArr.constructor.toString().indexOf("Array") == -1) {
        // For one item entries
        resArr = new Array();
        resArr[0] = arrObj;
    }
    return resArr;
}

function fixText(text){	
    var fixedText = text;
    if (fixedText != null && fixedText != "") {
        fixedText = fixedText.replace(/\r\n/g, " ");
        fixedText = fixedText.replace(/\n/g, " ");
        fixedText = fixedText.replace(/\r/g, " ");
        fixedText = fixedText.replace(/\'/g, "\\'");
        fixedText = fixedText.replace(/\"/g, '\\"');
    }
    return fixedText;
}

function clearErrDiv(elemID){
    var Node = document.getElementById(elemID);//errDiv
    if (Node != null)
        Node.innerHTML = "";
}

function createErrDiv(appenDiv){
    var appenDiv_obj = document.getElementById(appenDiv);
    var errDiv_obj = document.createElement("div");
        errDiv_obj.id = "errDiv";
        appenDiv_obj.appendChild(errDiv_obj);
}
function removeErrDiv(elemID){
    var Node = document.getElementById(elemID);//errDiv
        if(Node != null){
	  Node.parentNode.removeChild(Node);
        }
}
function createRegisterInput(appenID){
   var appen_obj = document.getElementById(appenID);
   if(appen_obj.innerHTML == ""){
    var tab_obj = document.createElement("table");
        tab_obj.cellSpacing = 0;
        tab_obj.cellPadding = 0;
        tab_obj.border= 0;
        tab_obj.id = "registerKeyTab";
        tab_obj.style.display = 'none'; 
    var tab_tr = tab_obj.insertRow(-1);

    var tab_td_1 = tab_tr.insertCell(-1);
        tab_td_1.className = "smalBB";
        tab_td_1.id = "inputTitle";
    var textTd_1 = document.createTextNode("Registration Key");
        tab_td_1.appendChild(textTd_1); 

    var tab_td_2 = tab_tr.insertCell(-1);
        tab_td_2.id = "inputTd";
        tab_td_1.className = "smalBB";
        tab_td_2.height = "49";
    var input = document.createElement("input");
        input.id = "registerKey";
        input.name = "registerKey";
        input.className = "loginInputs";
        input.value = "";
        tab_td_2.appendChild(input); 

        appen_obj.appendChild(tab_obj);
   }
}

var highresImg = "";
var highresImgId = "";
var lowresImg = "";
var lowresImgId = "";
var backgroundName = "";
var printUrl = "";

var HIGHRES_MAX_SIZE = "1400";
var LOWRES_MAX_SIZE = "800";

function checkHighres(currScene, currAspectRatio, currDuration) {
    // Link the face swap asset if not already there
    if (!highresImg || !highresImgId || currScene) {
        flattenSnapFunc = "printHighres";
        if (currScene) {
            // This is coming from the gallery
            callProcessWin();
            aspectRatio = currAspectRatio;
            assetDuration = currDuration;
            flattenSnapVideo(currScene, HIGHRES_MAX_SIZE);
        } else {
            flattenSnapVideo(scene, HIGHRES_MAX_SIZE);
        }
    } else {
        printHighres(highresImg, highresImgId);
    }
}
var flattenSnapFunc = "";
function checkLowres(nextFunc) {
    // Link the face swap asset if not already there
    if (!lowresImg || !lowresImgId) {
        flattenSnapFunc = nextFunc;
        flattenSnapVideo(scene, LOWRES_MAX_SIZE);
    } else {
        eval(nextFunc + "('" + lowresImg + "','" + lowresImgId + "')");
    }
}

function checkBackground(nextFunc) {
    // Link the face swap asset if not already there
    if (!backgroundName) {
        currRefresh = nextFunc;
        apiLinkFaceSwapChild(scene);
    } else {
        eval(nextFunc);
    }
}

// Use flattener snap to produce the images
function flattenSnapVideo(assetId, maxSize) {
    currRefresh = "flattenSnapDone";
    var xmlStr = createFlattenSnapXml(assetId, maxSize);
    doApiCreateAsset(xmlStr);
}

function createFlattenSnapXml(assetId, maxSize) {
    var calcWidth = maxSize;
    var calcHeight = maxSize;
    if (aspectRatio <= 1) {
        calcWidth = aspectRatio * maxSize;
    } else {
        calcHeight = (1 / aspectRatio) * maxSize;
    }
    var durationParm = assetDuration > 0 ? "<Duration>"+assetDuration+"</Duration>" : "";
    return getFlattenSnapXml(assetId, calcWidth, calcHeight, durationParm);
}
function getFlattenSnapXml(assetId, calcWidth, calcHeight, durationParm)
{
    var xmlStr = "<GizmozParams><OutputParams formatType=\"gizmoz/flatSnap\">" +
	"<ProfileId>8</ProfileId>" +
	"<OutputWidth>" + calcWidth + "</OutputWidth>" +
	"<OutputHeight>" + calcHeight + "</OutputHeight>" +
	"<Transparent>1</Transparent>" +
	"<Wait>1</Wait>" + durationParm +
	"</OutputParams>" +
	"<Assets><Asset id=\"" + assetId + "\" role=\"parent\"/></Assets>" +
	"<Attributes>" +
	    "<Attribute name=\"user_params\"></Attribute>" +
	    "<Attribute name=\"snapTime\">0</Attribute>" + 
	    "<Attribute name=\"web_callback\"><![CDATA[]]></Attribute>" +
	"</Attributes></GizmozParams>";
    return xmlStr;
}

function flattenSnapDone(assetId, contentUrl, contentWidth, contentHeight) { 
    // Go do what you need
    eval(flattenSnapFunc+"('"+contentUrl+"','"+assetId+"')");
}

// keep low and high res face swap images
function useFaceSwap(dataArray) {
    backgroundName = dataArray.backgroundName;
    if (currRefresh)
        eval(currRefresh);
}

// Download the lowres
function downloadLowres(contentUrl, assetId) {
    closeProcessWin();
    if (contentUrl) {
        lowresImg = contentUrl;
        lowresImgId = assetId;
        downloadItem(lowresImg + '&forceDownload=1');
    }
}

// Print the highres
function printHighres(contentUrl, assetId) {
    closeProcessWin();
    if (contentUrl && printUrl) {
        highresImg = contentUrl;
        highresImgId = assetId;    
        var printFullUrl = printUrl;
        printFullUrl += highresImg;
        window.open(printFullUrl);
    }
}

function downloadItem(itemUrl)
{
    confirm = false;
    document.location.href=itemUrl;
    confirm = true;
    return false;
}
// Use to interact with swf
function thisMovie(movieName) { 
    if (navigator.appName.indexOf("Microsoft") != -1) { 
        return window[movieName];
    } else { 
        return document[movieName];
    } 
}
//Gallery Class
function Gallery(
        type, galType, searchTags, andRelation, tagType, pageNum, quantityToShow, withStatistics, pagingType, colsNum, 
        propertyList, userList, itemId, trashEvent, pagingFunc, moreUrl, divName, nextFunction, imgUrl, butUrl, hitGA) {
    this.type = type;
    this.galType = galType;
    this.searchTags = searchTags;
    this.andRelation = andRelation;
    this.tagType = tagType;
    this.pageNum = (pageNum <= 1)?1:pageNum;
    this.startIndex = (quantityToShow * (this.pageNum-1))+1;
    this.toIndex = this.startIndex + quantityToShow-1;
    this.quantityToShow = quantityToShow;
    this.withStatistics = withStatistics;
    this.pagingType = pagingType;
    this.colsNum = colsNum;
    this.propertyList = propertyList;
    this.userList = userList;
    this.itemId = itemId;
    this.trashEvent = trashEvent;
    this.pagingFunc = pagingFunc;
    this.divName = divName;
    this.nextFunction = nextFunction;
    this.moreUrl = moreUrl;
    this.imgUrl = imgUrl;
    this.butUrl = butUrl;
    this.data = null;
    if(hitGA) {
        this.hitGA = hitGA.replace("{galleryTipe}",galType);
   }
}
function setGalData(data) {
    this.data = data;
}
function getGalData() {
    return this.data;
}
Gallery.prototype.setGalData = setGalData;
Gallery.prototype.getGalData = getGalData;
//Gallery Class End

// Partner properties
function PartnerProperties() {
    this.defaultHeadId = "";
    this.defaultTorso = "";
}

// User properties
function UserProperties() {
    this.id = 0;
    this.creator = "";
    this.title = "";
    this.createdDay = "";
    this.creatorJoined
    this.totalVideos = 0;
    this.remixed = 0;
    this.rating = 0;
    this.img = "";
    this.imgUrl = "";
    this.moreUrl = "";
    this.butUrl = "";
    this.password = "";
    this.privateUserProperties = null;
}

function setPrivateUserProperties(privateUserProperties) {
    this.privateUserProperties = privateUserProperties;
}

function getPrivateUserProperties() {
    return this.privateUserProperties;
}

function PrivateUserProperties() {
    this.firstName = "";
    this.lastName = "";
    this.gender = "";
    this.birthday = "";
    this.country = "";
    this.town = "";
    this.email = "";
    this.personalWebsite = "";
    this.blog = "";
    this.hobbies = "";
    this.aboutMe = "";
    this.allowUpdates = "";
}

UserProperties.prototype.setPrivateUserProperties = setPrivateUserProperties;
UserProperties.prototype.getPrivateUserProperties = getPrivateUserProperties;

function AssetProperties() {
    this.id =  0;
    this.img = "";
    this.previewImg = "";
    this.imgUrl = "";
    this.title = "";
    this.creator = "";
    this.createdDay = "";
    this.addedDay = "";
    this.remixed = 0;
    this.duration = 0;
    this.rating = 0;
    this.creatorJoined = 0;
   // this.creatorsRating = 0;
    this.totalVideos = 0;
    this.views = 0;
    this.butUrl = "";
    this.trashEvent = "";
    this.popTempStar = 0; 
    this.description = "";
    this.tags = ""; 
    this.authorization = "";
    this.gender = "";
    this.type = "";
    this.subtype = "";
}

function CommentProperties() {
    this.id =  0;
    this.img = "";
    this.imgUrl = "";
    this.title = "";
    this.creator = "";
    this.creatorId = "";
    this.createdDay = "";
    this.timeAgo = "";
    this.description = "";
    this.creatorJoined = 0;
  //  this.creatorsRating = 0;
    this.butUrl = "";
    this.trashEvent = "";
    this.abuseEvent = "";
}

function addSelectOption(selectObj,txt,val)
{
    var elOptNew = document.createElement('option');
    elOptNew.text =txt;
    elOptNew.value = val;
    try {
	selectObj.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
	selectObj.add(elOptNew); // IE only
    }
}
function selectIndexOf(selectObj,txt)
{
    var i, entry, name;
    for (i = 0; i<selectObj.length; i++)
	if (selectObj[i].text == txt)
	    return i;
    return -1;
}
function set_cookie(name, value, expires) {
    if (!expires){
	expires = new Date();
    }
   document.cookie = name+'='+ value+'; expires='+expires+'; path=/';
}
function get_cookie(name){
cookie_name = name + "=";
cookie_length = document.cookie.length;
cookie_begin = 0;
while (cookie_begin < cookie_length){
    value_begin = cookie_begin + cookie_name.length;
    if (document.cookie.substring(cookie_begin, value_begin) == cookie_name){
    var value_end = document.cookie.indexOf (";", value_begin);
	if (value_end == -1){
	    value_end = cookie_length;
	}
    return unescape(document.cookie.substring(value_begin, value_end));
    }
    cookie_begin = document.cookie.indexOf(" ", cookie_begin) + 1;
	if (cookie_begin == 0){
	    break;
	}
    }
    return null;
}