// Search label hiding / population
function hideText(element, sText) {
    if (element.value == sText) {
        element.value = '';
    }
    element.select();
}

function showText(element,sText) {
    if (!element.value.length) {
        element.value = sText;
    }
}

// Set the following variable to 'false' to set the title
// of the item identified by the id.  Set it to 'true' to
// set the title of the first <p> tag inside that item
// instead.
var uglyParagraphPatch = true;

function toggleItems(ison,isoff) {
  if(ison != '')
  	document.getElementById(ison).style.display = 'none';
  if(isoff != '')
  	document.getElementById(isoff).style.display = 'block';
}

function unfoldList(theitem) {
   var item = document.getElementById(theitem);
   if((item.className == 'fold'))
      item.className = 'unfold';
   else
      item.className = 'fold';

   var label = getToggleListLabel(theitem, item.className);
	if(label != undefined) {
		if(uglyParagraphPatch) {
			var paras = item.getElementsByTagName("p");
			if(paras.length>0) {
				paras[0].title=label;
			}
		} else {
			item.title=label;
		}
	}
}

var toggleLists = {};
function setToggleListLabel(list, clazz, label) {
	var item = toggleLists[list];
	if(item == undefined) {
		toggleLists[list] = {};
	}
	toggleLists[list][clazz] = label;
}

function getToggleListLabel(list, clazz) {
	var label = undefined;
	if(toggleLists[list] != undefined) {
		label = toggleLists[list][clazz];
	}
	return label;
}

function initToggleListLabels(clazz) {
	for(var listId in toggleLists) {
		var item = document.getElementById(listId);
		var label = getToggleListLabel(listId, item.className);
		if(label != undefined) {
			if(uglyParagraphPatch) {
				var paras = item.getElementsByTagName("p");
				if(paras.length>0) {
					paras[0].title=label;
				}
			} else {
				item.title=label;
			}
		}
		if(clazz != undefined) {
			item.className=clazz;
		}
	}
}

function toggleOneItem(theitem) {
  if((document.getElementById(theitem).style.display == 'block') || (document.getElementById(theitem).style.display == -1))
    document.getElementById(theitem).style.display = 'none';
  else
    document.getElementById(theitem).style.display = 'block';
}

function toggleTwoItem(theitem1, theitem2) {
  if((document.getElementById(theitem1).style.display == 'none') || (document.getElementById(theitem1).style.display == -1))
  {
    document.getElementById(theitem1).style.display = 'block';
    document.getElementById(theitem2).style.display = 'none';
  }
}

function toggleClass(theitem) {
  if((document.getElementById(theitem).className == 'close'))
    document.getElementById(theitem).className = 'open';
  else
    document.getElementById(theitem).className = 'close';
}

function changeClassName(theitem, NewclassName) {
  if((document.getElementById(theitem).className != NewclassName)) {
    document.getElementById(theitem).className = NewclassName;
  }
}

function enableSubmit(checkBoxID, buttonID) {
	if(document.getElementById(checkBoxID).checked == true) {
		document.getElementById(buttonID).disabled = false;
		changeClassName(buttonID,'alignRight enabled');
	}
	else {
		document.getElementById(buttonID).disabled = true;
		changeClassName(buttonID,'alignRight disabled');
	}
}

var checkflag = "false";
function check(field) {
  if (checkflag == "false") {
    for (i = 0; i < field.length; i++) {
      field[i].checked = true;
    }
    checkflag = "true";
    return "Uncheck All";
    } else {
      for (i = 0; i < field.length; i++) {
      field[i].checked = false;
    }
    checkflag = "false";
    return "Check All"; }
}

var speed = 5;
var target = -3;

function yMove(objectID) {
  var objMove = document.getElementById(objectID)

  if (parseInt(objMove.style.top) < target) {
    objMove.style.top=parseInt(objMove.style.top)+speed+"px"
    yMoveVar = setTimeout("yMove('"+objectID+"')",20)
  } else {
    clearTimeout(yMoveVar);
  }
}

var targetHide = -108;

function yHide(objectID) {
  var objMove = document.getElementById(objectID)

  if (parseInt(objMove.style.top) > targetHide) {
    objMove.style.top=parseInt(objMove.style.top)-speed+"px"
    var yHideVar = setTimeout("yHide('"+objectID+"')",20)
  } else {
    clearTimeout(yHideVar);
  }
}

function setFlashWidth(divid, newW){
	document.getElementById(divid).style.width = newW+"px";
	//alert(newW);
}
function setFlashHeight(divid, newH){
	document.getElementById(divid).style.height = newH+"px";
	//alert(newH);
}
function setFlashSize(divid, newW, newH){
	setFlashWidth(divid, newW);
	setFlashHeight(divid, newH);
	//alert(newW + '/' + newH);
}
function canResizeFlash(){
	var ua = navigator.userAgent.toLowerCase();
	var opera = ua.indexOf("opera");
	if( document.getElementById ){
		if(opera == -1) return true;
		else if(parseInt(ua.substr(opera+6, 1)) >= 7) return true;
	}
	return false;
}

function flashToUrl(url, method) {
	var method;
	if (!method) {
		location.href = url;
	} else if(method == '_blank') { // if flash movie set a variable _blank we open in a new window
		window.open (url,'new','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes'+',width='+800+',height='+600+',left='+25+',top='+25);
	}
	sendModifiedOmniturePageName('flashlink');
}


function gotoSite(thisUrl, thisWidth,thisHeight,thisTop,thisLeft) {

     var url = '/shopping/popups/personal/leaving.jsp?url=' + thisUrl;
     optionString = ('width=' + thisWidth + ',height=' + thisHeight + ',top=' + thisTop + ',left=' + thisLeft + ',status=no,menubar=no,resizable=yes,scrollbars=yes');
     mainWin = window.open(url,'goExternal',optionString);

 }

 function rollover(obj){
	var src = "";
	if(document.getElementById(obj).src.indexOf('off')!=-1){
		src = document.getElementById(obj).src.replace('off','over');
	}else if(document.getElementById(obj).src.indexOf('over')!=-1){
		src = document.getElementById(obj).src.replace('over','off');
	}
	document.getElementById(obj).src = src;
}

function updateProgressBar(inputProgress){
	if (inputProgress < 100) {
		document.getElementById("progress_update").innerHTML = inputProgress + '%<span>uploaded</span>';
	}
	else if (inputProgress == 100) {
		document.getElementById("progress_update").innerHTML = inputProgress + '%<span>completed</span>';
	}

	document.getElementById("progress_bar").style.width = inputProgress + '%';
}

function updateIframeSrc(iframeName, source) {
	document.getElementById(iframeName).src = source;
}

function updateDiv(divName, content) {
	document.getElementById(divName).innerHTML = content;
}

function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}

	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);

	if(TRIM_VALUE==""){
		return "";
	}

	else{
		return TRIM_VALUE;
	}

} //End Function



function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";

	if(v_length < 0){
		return"";
	}

	var iTemp = v_length -1;

	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}

		iTemp = iTemp-1;

	} //End While

	return strTemp;

} //End Function



function LTrim(VALUE){
	var w_space = String.fromCharCode(32);

	if(v_length < 1){
		return"";
	}

	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;

	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){}
			else{
				strTemp = VALUE.substring(iTemp,v_length);
				break;
			}
			iTemp = iTemp + 1;
	} //End While

	return strTemp;

} //End Function

function checkAll(checkboxName) {
	var el = document.getElementsByName(checkboxName);
	for(i=0;i<el.length;i++){
		el[i].checked = true;
	}
}

function uncheckAll(checkboxName) {
	var el = document.getElementsByName(checkboxName);
	for(i=0;i<el.length;i++){
		el[i].checked = false;
	}
}

function showWarning(msg, xtype, rtnFunctionName) {
	// xtype - if 1: there will be 2 buttons, cancel and ok, else it will be only ok

	// rtnFunctionName - will return true of false to the function name enter here
	// ie: if rtnFunctionName = 'myFunction', for the button cancel we will have onClick="myFunction(False)"
	//     if rtnFunctionName = 'myFunction', for the button ok we will have onClick="myFunction(True)"
	var content = '';
	content = '<p>' + msg + '</p><p>';

	// add the cancel button
	if (xtype == 1) {
		content += '<a href="javascript: return false;" class="lbAction" rel="deactivate"><img src="../base/image/buttonCancel.gif" alt="Cancel" title="Cancel" border=0';
		if (rtnFunctionName != null && rtnFunctionName != '' && rtnFunctionName != undefined && rtnFunctionName != false) {
			content += ' onClick="'+rtnFunctionName+'(false);"';
		}
		content += ' /></a>';
	}

	content += '<a href="javascript: return false;" class="lbAction" rel="deactivate"><img src="../base/image/buttonOk.gif" alt="Ok" title="Ok" border=0';

	if (xtype == 1)
		content += ' hspace="10"';

	content += '"';

	if (rtnFunctionName != '')
		content += ' onClick="'+rtnFunctionName+'(true);"';

	content += ' /></a>';

	content += '</p>';

	document.getElementById('msgWarning').innerHTML = content;
	document.frmWarning.reset();
}

function isEmail(str) {
	var r = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
	return (r.test(str));
}

// Sky Credentials Popup
function popupSkyCredentials (tier,downgrade,username,expiry) {
    if (downgrade == true) {
        credentialWizard.initialize(tier,username,expiry);
    } else {
        $('statusMessage').innerHTML = "<p>You are storing too many files for the account you have selected. To downgrade your account you will need to delete files from your online Store space. Please use the 'Storage Use' bar to ensure that the size of your files does not exceed the allowance for the account you have selected.</p><p>You can delete files using the 'Delete Files' tab in the Backup Manager or by clicking 'Delete' on individual files from your Store space.</p>";
        $('statusMessage').style.display = "block";
    }
}

credentialWizard = {
    initialize: function (tier,username,expiry) {
        this.tier = tier;
        new Wizard ({
            html: '',
            height: '330',
            width: '640',
            shadow: 'true',
            form: {
                id: "credentialForm",
                name: "credentialForm",
                action: "/abode/customer/SkySubscription.action"
            }
        });

        this.credentialCheck.init(tier,username,expiry);
    },

    credentialCheck: {
        init: function (tier,username,expiry) {
            $('previous').hide();
            new Ajax.Updater('popupContent', '/settings/include/skyPopup.jsp', {

                method: 'post',
                evalScripts:true,
                onFailure: function() {location.href = '/error/error401.jsp';},

                onComplete: function() {
                    $('next').onclick = function(){
                        var url="/abode/customer/SkySubscription.action";

                        var sUsername = $('skyUsername').value;
                        var sPassword = $('skyPassword').value;

                        var pars = new Hash({skyUserName: sUsername, skyPassword: sPassword, accountType: tier});

                        if (!sUsername.length || !sPassword.length) {
                            $('skyCredentialError').innerHTML = "Please enter both your sky.com username and password.";
                        } else {
                            // show progress and disable next button and hide errors
                            $('next').disabled = true;
                            $('skyCredentialError').style.display = "none";
                            $('progress').innerHTML = "<img src='/base/image/progress.gif' alt='Please wait...' />";
                            $('progress').style.display = "block";


                            new Ajax.Request(url, {
                                parameters: pars,
                                on200: function(t) {
                                    // switch current account
                                    //$$('.current')[0].className = "upgrade";
                                    //$(tier).className = "current";

                                    // update account manager page
                                    var that = thisPopUp;
                                    that.remove();

                                    //$('statusMessage').innerHTML = "Your account has been updated successfully!";
                                    //$('statusMessage').style.display = "block";
                                    document.location = '/settings/accountManagement.jsp';
                                },

                                on201: function(t) {
                                    // redirect to MPP
                                    var formHTML = t.responseText;
                                    $('mppFormHolder').innerHTML = formHTML;
                                    $('progress').style.display = "none";
                                    $('mppPayment').submit();
                                },

                                on401: function(t) {
                                    // sky account authorization failed
                                    var errorMsg = t.responseText;
                                    // alert( errorMsg);
                                    $('skyCredentialError').innerHTML = errorMsg;
                                    $('skyCredentialError').style.display = "block";

                                    // hide progress and enable next button
                                    $('progress').style.display = "none";
                                    $('progress').innerHTML = "";
                                    $('next').disabled = false;
                                }
                            });
                        }
                    }
                    $('accountType').value=tier;

                    if (username) {
                        // set username and disable field
                        $('skyUsername').value = username;
                        $('skyUsername').disabled = true;
                    }

                    if (expiry) {
                        // Set expiry date
                        $('skyExpiryDate').innerHTML = expiry;
                        // Show expiry msg
                        $('skyExpiryMsg').style.display = "block";
                    }
                }
            });
        }
    }
}

// Sky Backup Manager Credentials Popup
function popupSkyBkupMngCredentials (tier,downgrade,username,expiry,backupmanager) {
    if (backupmanager == true) {
		autoSubmitWizard.initialize(tier,username,expiry);        
    } else {
        credentialWizard.initialize(tier,username,expiry);
    }
}
    
credentialWizard = {
    initialize: function (tier,username,expiry) {
        this.tier = tier;
        new Wizard ({
            html: '',
            height: '230',
            width: '540',
            shadow: 'true',
            form: {
                id: "credentialForm",
                name: "credentialForm",
                action: "/abode/customer/SkySubscription.action"
            }
        });

        this.credentialCheck.init(tier,username,expiry);
    },

    credentialCheck: {
        init: function (tier,username,expiry) {
            $('previous').hide();
            new Ajax.Updater('popupContent', '/settings/include/skyBackupManagerPopup.jsp', {
				
                method: 'post',
                evalScripts:true,
                onFailure: function() {location.href = '/error/error401.jsp';},
                 
                onComplete: function() {
                    $('autoSubmitTitle').hide();
                    $('next').onclick = function(){
                        
                        var url="/abode/customer/SkySubscription.action";
						
						var sUsername = '';
                        var sPassword = $('skyPassword').value;
                        var sConfirmPassword = $('skyConfirmPassword').value;
						var specialChar1 =/\s/;
						var specialChar2 =/[0-9]/;
						var specialChar3 =/[a-zA-Z]/;
						
                        var pars = new Hash({skyUserName: sUsername, skyPassword: sPassword, accountType: tier});
                         
                        if (!sPassword.length || !sConfirmPassword.length) {
                            $('skyCredentialError').innerHTML = "Please enter both your password and confirm password.";
                            return false;
                        } else if ( specialChar1.test(sPassword)) {
                            $('skyCredentialError').innerHTML = "Your password can contain only alphanumeric or punctuation characters and must be between 8 and 16 characters long.";
                            return false;
                        } else if ( !specialChar2.test(sPassword) || !specialChar3.test(sPassword)) {
                            $('skyCredentialError').innerHTML = "Your password must contain at least one number and letter.";
                            return false;
                        } else if ( sPassword.length < 8 || sPassword.length > 16) {
                            $('skyCredentialError').innerHTML = "Your password must contain between 8 and 16 characters long.";
                            return false;
                        } else if ( sPassword != sConfirmPassword ) {
                            $('skyCredentialError').innerHTML = "Your password and confirm password do not match.";
                            return false;
                        } else {
                            // show progress and disable next button and hide errors
                            $('next').disabled = true;
                            $('skyCredentialError').style.display = "none";
                            $('progress').innerHTML = "<img src='/base/image/progress.gif' alt='Please wait...' />";
                            $('progress').style.display = "block";


                            new Ajax.Request(url, {
                                parameters: pars,
                                on200: function(t) {
                                    // switch current account
                                    //$$('.current')[0].className = "upgrade";
                                    //$(tier).className = "current";

                                    // update account manager page
                                    var that = thisPopUp;
                                    that.remove();

                                    //$('statusMessage').innerHTML = "Your account has been updated successfully!";
                                    //$('statusMessage').style.display = "block";
                                    document.location = '/settings/accountManagement.jsp';
                                },

                                on201: function(t) {
                                    // redirect to MPP
                                    var formHTML = t.responseText;
                                    $('mppFormHolder').innerHTML = formHTML;
                                    $('progress').style.display = "none";
                                    $('mppPayment').submit();
                                },

                                on401: function(t) {
                                    // sky account authorization failed
                                    var errorMsg = t.responseText;
                                    // alert( errorMsg);
                                    $('skyCredentialError').innerHTML = errorMsg;
                                    $('skyCredentialError').style.display = "block";

                                    // hide progress and enable next button
                                    $('progress').style.display = "none";
                                    $('progress').innerHTML = "";
                                    $('next').disabled = false;
                                }
                            });
                        }
                    }
                    $('accountType').value=tier;

                  //  if (username) {
                        // set username and disable field
                     //   $('skyUsername').value = username;
                      //  $('skyUsername').disabled = true;
                  //  }

                    if (expiry) {
                        // Set expiry date
                        $('skyExpiryDate').innerHTML = expiry;
                        // Show expiry msg
                        $('skyExpiryMsg').style.display = "block";
                    }
                }
            });
        }
    }
}

autoSubmitWizard = {
    initialize: function (tier,username,expiry) {
        this.tier = tier;
        new Wizard ({
            html: '',
            height: '150',
            width: '380',
            shadow: 'true',
            form: {
                id: "credentialForm",
                name: "credentialForm",
                action: "/abode/customer/SkySubscription.action"
            }
        }); 
        this.autoCheck.init(tier,username,expiry);
    },
    
    autoCheck: {
        init: function (tier,username,expiry) {
            $('previous').hide();
            $('next').hide();
            $('closePopup').hide();
            new Ajax.Updater('popupContent', '/settings/include/skyBackupManagerPopup.jsp', {				
                method: 'post',
                evalScripts:true,
                onFailure: function() {location.href = '/error/error401.jsp';},                 
                onComplete: function() {
                       $('backupTitle').hide();
                       $('skyCredentials').hide();
					   var pars = new Hash({accountType: tier});

                       $('autoSubmitTitle').style.display = "block";                       
                       var url="/abode/customer/SkySubscription.action";
                       
                      // show progress and disable next button and hide errors
                      $('skyCredentialError').style.display = "none";
                      $('progress').innerHTML = "<img src='/base/image/progress.gif' alt='Please wait...' />";
                      $('progress').style.display = "block";
                      $('progress').style.padding = "0";


                      new Ajax.Request(url, {
                      	  parameters: pars,
                          on200: function(t) {
                              // switch current account
                              //$$('.current')[0].className = "upgrade";
                              //$(tier).className = "current";

                              // update account manager page
                              var that = thisPopUp;
                              that.remove();

                              //$('statusMessage').innerHTML = "Your account has been updated successfully!";
                              //$('statusMessage').style.display = "block";
                              document.location = '/settings/accountManagement.jsp';
                          },

                          on201: function(t) {
                              // redirect to MPP
                              var formHTML = t.responseText;
                              $('mppFormHolder').innerHTML = formHTML;
                              $('progress').style.display = "none";
                              $('mppPayment').submit();
                          },

                          on401: function(t) {
                              // sky account authorization failed
                              var errorMsg = t.responseText;
                              // alert( errorMsg);
                              $('skyCredentialError').innerHTML = errorMsg;
                              $('skyCredentialError').style.display = "block";

                              // hide progress and enable next button
                              $('progress').style.display = "none";
                              $('progress').innerHTML = "";
                              $('next').disabled = false;
                          }
                       });  
                       
	                    $('accountType').value=tier;
	                    if (expiry) {
	                        // Set expiry date
	                        $('skyExpiryDate').innerHTML = expiry;
	                        // Show expiry msg
	                        $('skyExpiryMsg').style.display = "block";
	                    }
                                          
                    }
                    

            });
           
           }
    }
}