dojo.require("dojo.back");
//dojo.require("dijit.form.DateTextBox");
/** definitions **/
var serverRoot = 'Web';
var ContactsFilter;
var currentPage;

function trimNull(str){
    if (str.indexOf('0') == 0) {
        return str.slice(1);
    }
    else {
        return str;
    }
}

getEvent = function(e){
    var evt = e || window.event;
    return evt;
}

function getEventTarget(e){
    var targ;
    
    e = getEvent(e);
    if (e.target) {
        targ = e.target;
    }
    else 
        if (e.srcElement) {
            targ = e.srcElement;
        }
    if (targ.nodeType == 3) { // defeat Safari bug
        targ = targ.parentNode;
    }
    return targ;
}

function initHistory(url){
    var appState = new ApplicationState(url, null, null);
    dojo.back.setInitialState(appState);
}

function ApplicationState(uri, params, extra, changeUrl){
    this.uri = uri;
    this.params = params;
    this.outputDivId = 'content';
    this.extra = extra;
    
    if (typeof( window[ '_gat' ] ) != "undefined" && changeUrl) {
		try {
			var pageTracker = _gat._getTracker("UA-6164049-2");
			pageTracker._trackPageview("/" +
			changeUrl // special cases we don't want to track
	// should receive the two portions as separate params, but that will wait until LoadData is refactored
			.replace(/^photosOpen-\w+$/, "photosOpen") //registration tokens WILL show as separate pages, but there's less we can do aboout it (GET-params)
);
		}catch(e){
			
		}
	}
    this.changeUrl = changeUrl;
    this.back = function(){
        LoadData(this.uri, this.outputDivId, this.params, this.extra, true);
    };
    this.forward = function(){
        LoadData(this.uri, this.outputDivId, this.params, this.extra, true);
    };
}


var commonJson;
function AjaxParse(response, handler){
	commonJson = null;
    if (response.slice(4, 14) == "JSON_START") {
    
        var jsonEnd = response.indexOf('JSON_END');
        var strJSON = response.slice(14, jsonEnd);
        if (strJSON && strJSON.length > 0) {
            var objJSON = eval('(' + strJSON + ')');
            if (objJSON) {
                commonJson = objJSON;
                handler();
            }
        }
        if (jsonEnd && jsonEnd > 0) {
            return response.slice(jsonEnd + 12);
        }
    }
    return response;
}

function LoadData(uri, target, post, extra, notSaveToHistory, changeUrl){
    if (target == 'content' && !notSaveToHistory) {
        var appState = new ApplicationState(uri, post, extra, changeUrl);
        dojo.back.addToHistory(appState);
    }
    params = {
        url: uri,
        handleAs: "text",
        content: post,
        load: function(response, ioArgs){
            nd();
            if (response == 'NOSESSION') {
                window.location = 'LoginController.do';
                return;
            }
            response = AjaxParse(response, function(){
                if (commonJson.messageToDisplay) {
                    popUpDialog('notice', commonJson.messageToDisplay, 'Attention');
                }
                if (commonJson.errorType) {
                    popUpDialog('notice', commonJson.errorMessage, 'Error');
                }
                runPostLoadAction();
            });
            if (target && dojo.byId(target)) {
                dojo.byId(target).innerHTML = response;
            }
            if (extra && extra.postLoad) {
                extra.postLoad(response);
            }
            if (globalPostLoad) {
                globalPostLoad();
            }
            document.title = 'VUFONE';
            removeActions();
            return response;
        },
        error: function(response, ioArgs){
            console.error("HTTP status code: ", ioArgs.xhr.status);
            document.title = 'VUFONE';
            return response;
        }
    }
    dojo.xhrPost(params);
}

function LoadHtmlToPopup(uri, post, title, func, extra){
    dojo.query('.flash').style('visibility', 'hidden');
    params = {
        url: uri,
        handleAs: "text",
        content: post,
        sync: true,
        load: function(response, ioArgs){
            response = AjaxParse(response);
            popUpDialog('form', response, title, func);
            if (extra && extra.postLoad) {
                extra.postLoad();
            }
            return response;
        },
        error: function(response, ioArgs){
            console.error("HTTP status code: ", ioArgs.xhr.status);
            return response;
        }
    }
    dojo.xhrPost(params);
}

function LoadHtmlToAddFilePopup(uri, post, title, func){
    dojo.query('.flash').style('visibility', 'hidden');
    params = {
        url: uri,
        handleAs: "text",
        content: post,
        sync: true,
        load: function(response, ioArgs){
            response = AjaxParse(response);
            popUpDialog('fileForm', response, title, func);
            return response;
        },
        error: function(response, ioArgs){
            console.error("HTTP status code: ", ioArgs.xhr.status);
            return response;
        }
    }
    dojo.xhrGet(params);
}

/** contacts **/


function ScrollTo(selector, coord){
    var node = dojo.query(selector)[0];
    if (node) {
        node.scrollTop = coord;
    }
}

function delayedFilter(func){
    dojo.query('.filtering .progress').removeClass = 'invisible';
    filterTimeout = setTimeout(func, 1000);
}

function popUpDialog(type, text, title, func, modal, noFunc){
    var type = (type || 'alert')
    var caption = (title || '');
    var modal = (modal || true);
    switch (type) {
        case 'sysMessage':
            var popupContent = dojo.byId('text_sysMessage_box_conteiner').innerHTML;
            break;
        case 'excl':
            var popupContent = dojo.byId('excluzive_text_alert_box_conteiner').innerHTML;
            break;
        case 'notice':
            var popupContent = dojo.byId('text_notice_box_conteiner').innerHTML;
            break;
        case 'info':
            var popupContent = dojo.byId('text_info_box_conteiner').innerHTML;
            break;
        case 'alert':
            var popupContent = dojo.byId('text_alert_box_conteiner').innerHTML;
            break;
        case 'form':
        case 'fileForm':
            var popupContent = dojo.byId('form_conteiner').innerHTML;
            break;
        case 'tooltip':
            var popupContent = text;
            break;
        default:
            var popupContent = text;
    }
    if (type != 'tooltip') {
        dojo.query('.flash').style('visibility', 'hidden');
        var rExp = /MESSAGECONTENT/gi;
        popupContent = popupContent.replace(rExp, text);
        var rExp = /YESFUNCTION/gi;
        popupContent = popupContent.replace(rExp, func);
        var rExp = /NOFUNCTION/gi;
        popupContent = popupContent.replace(rExp, noFunc);
        //if (typeof(hideFlash) == 'function') {
        //   hideFlash();
        //}
    }
    switch (type) {
        case 'sysMessage':
        case 'excl':
        case 'alert':
        case 'confirm':
        case 'notice':
        case 'info':
            myConfirmDialog = overlib(popupContent, EXCLUSIVEOVERRIDE, caption ? CAPTION : DONOTHING, caption ? caption : DONOTHING, CLOSECLICK, CLOSETEXT, '<div onclick="closePopUp();" class="buttonClose" ></div>', CAPTIONPADDING, 4, TEXTPADDING, 10, BGCLASS, 'olbgD', BORDER, 2, CGCLASS, 'olcgD', CAPTIONFONTCLASS, 'olcapD', CLOSEFONTCLASS, 'olcloD', FGCLASS, 'olfgD', TEXTFONTCLASS, 'oltxtD', SHADOW, SHADOWCOLOR, '#888888', MODAL, WIDTH, 300, STICKY, EXCLUSIVE, SCROLL, MIDX, 0, MIDY, 0, REFC, 'UL', REFP, 'UL', MODALSCROLL);
            break;
        case 'form':
            myConfirmDialog = overlib(popupContent, EXCLUSIVEOVERRIDE, caption ? CAPTION : DONOTHING, caption ? caption : DONOTHING, CLOSECLICK, CLOSETEXT, '<div onclick="closePopUp();" class="buttonClose" ></div>', CAPTIONPADDING, 4, TEXTPADDING, 10, BGCLASS, 'olbgD', BORDER, 2, CGCLASS, 'olcgD', CAPTIONFONTCLASS, 'olcapD', CLOSEFONTCLASS, 'olcloD', FGCLASS, 'olfgD', TEXTFONTCLASS, 'oltxtD', SHADOW, SHADOWCOLOR, '#888888', MODAL, WIDTH, 676, HEIGHT, 394, STICKY, EXCLUSIVE, SCROLL, MIDX, 0, MIDY, 0, REFC, 'UL', REFP, 'UL', MODALSCROLL);
            break;
        case 'fileForm':
            myConfirmDialog = overlib(popupContent, EXCLUSIVEOVERRIDE, caption ? CAPTION : DONOTHING, caption ? caption : DONOTHING, CLOSECLICK, CLOSETEXT, '<div onclick="closePopUp();" class="buttonClose" ></div>', CAPTIONPADDING, 4, TEXTPADDING, 10, BGCLASS, 'olbgD', BORDER, 2, CGCLASS, 'olcgD', CAPTIONFONTCLASS, 'olcapD', CLOSEFONTCLASS, 'olcloD', FGCLASS, 'olfgD', TEXTFONTCLASS, 'oltxtD', /*SHADOW, SHADOWCOLOR, '#888888',*/ MODAL, WIDTH, 350, HEIGHT, 130, STICKY, EXCLUSIVE, SCROLL, MIDX, 0, MIDY, 0, REFC, 'UL', REFP, 'UL', MODALSCROLL);
            break;
        case 'tooltip':
            myConfirmDialog = overlib(text, TEXTSIZE, 2, WRAP, FILTER, FADEIN, 49, FADEOUT, 0)
    }
}

function closePopUp(){
    cClick();
    dojo.query('.flash').style('visibility', 'visible');
}

/**********************************************************************/
function selectAll(pattern){
    var queryString = "input[type='checkbox'][name='" + pattern + "']";
    var list = dojo.query(queryString).filter(function(item){
        return (!dojo.hasClass(item.parentNode.parentNode, 'hidden'));
    });
    var c = false;
    
    list.forEach(function(item){
        if (item.checked == false) {
            c = true;
        };
            });
    list.forEach(function(item){
        if (item.clientWidth > 0) {
            item.checked = c;
        }
    });
}

function copyValue(sourseId, targetId){
    if (dojo.byId(targetId) && dojo.byId(sourseId)) {
        dojo.byId(targetId).value = dojo.byId(sourseId).value;
    }
}

function setValue(id, value){
    dojo.byId(id).value = value;
}

function getValue(id){
    if (dojo.byId(id)) {
        return dojo.byId(id).value;
    }
    else {
        return null;
    }
}

/***********************************************/
function is_child_of(parent, child){
    if (child != null) {
        while (child.parentNode) {
            if ((child = child.parentNode) == parent) {
                return true;
            }
        }
    }
    return false;
}

// returns the innermost ancestor element of node (node itself qualifies as well)
//      with the specified class, or null if none was found
function getAncestorWithClass(node, class_){
    try {
        while (node) {
            if (dojo.hasClass(node, class_)) {
                return node; // Boolean
            }
            node = node.parentNode;
        }
    } 
    catch (e) { /* squelch */
    }
    return null; // Boolean
}

function firstFocus(node){
    node.value = '';
    node.onfocus = null;
    dojo.removeClass(node, "initHint");
}

function fixOnMouseOut(element, event, JavaScript_code){
    var current_mouse_target = null;
    if (event.toElement) {
        current_mouse_target = event.toElement;
    }
    else 
        if (event.relatedTarget) {
            current_mouse_target = event.relatedTarget;
        }
    //alert(current_mouse_target.className);
    //alert(is_child_of(element, current_mouse_target));
    //alert(element != current_mouse_target);
    if (!is_child_of(element, current_mouse_target) && element != current_mouse_target) {
        //if(element.id == current_mouse_target.id || current_mouse_target.className == element.className){
        eval(JavaScript_code);
    }
}


function FileExt(str){
    var match = str.match(/\.([^\.]+)$/);
    return (match ? match[0] : "");
}

/**************************************************/
// function for changing stylesheets using document.styleSheets
function setStyleSheet(theme){
    if (dojo.query("#sidebar_vcard .name")[0]) {
        var uri = 'UserSettingsController.do';
        var post = {
            action: 'saveHeaderColor',
            colorID: isNaN(theme) ? 1 : theme
        };
        LoadData(uri, null, post, null);
    }
    var themeName = 'theme' + theme;
    for (i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].title) {
            document.styleSheets[i].disabled = true;
            if (document.styleSheets[i].title == themeName) {
                document.styleSheets[i].disabled = false;
            }
        }
    }
}

/**************************************************/

function PD(obj){
    var strOut = '';
    for (key in obj) {
        strOut += key + ':' + obj[key] + '\n';
    }
    alert(strOut);
}

function test(h){
    alert(h);
}

/*********************************/
function picTypeSelect(optNode, imgPath){
    dojo.byId('contact_picture_pic_img').src = imgPath;
    dojo.byId('contact_main_pic_img').src = imgPath;
    optNode.checked = true;
}

/********** Registration ************/
function registerAction(){
    var form = document.getElementById('login_register_form');
    var arrLoginCheckItems = [{
        id: 'login_register_country',
        name: 'Country',
        checks: [{
            type: 'isNotEmpty',
            message: 'The %name% field is empty'
        }, {
            type: 'isNumeric',
            message: 'The %name% field is invalid'
        }]
    }, {
        id: 'login_register_phone',
        name: 'Phone',
        checks: [{
            type: 'isNotEmpty',
            message: 'The %name% field is empty'
        }, {
            type: 'isNumeric',
            message: 'The %name% field is invalid'
        }]
    }, {
        id: 'login_register_email',
        name: 'Email',
        checks: [{
            type: 'email',
            message: 'The %name% field is not valid email'
        }]
    }, {
        id: 'login_register_firstname',
        name: 'First Name',
        checks: [{
            type: 'isNotEmpty',
            message: 'The %name% field is empty'
        }]
    }, {
        id: 'login_register_lastname',
        name: 'Last Name',
        checks: [{
            type: 'isNotEmpty',
            message: 'The %name% field is empty'
        }]
    }];
    var boolValid = fieldsValidation(arrLoginCheckItems);
    if (form && boolValid) {
        form.submit();
    }
}

/********** Login ****************/
function loginAction(){
    var form = document.getElementById('login_form');
    if (form) {
        form.submit();
    }
}

function handleKeyDownEnter(event, query, action_func){
    if (event.keyCode == 13 &&
    dojo.query(query).every(function(item){
        return item.value
    })) {
        action_func();
    }
}

/******** header ****/

function fixInputFocus(selector){
    var inputs = dojo.query(selector);
    
    /*	inputs.forEach( function(item, index) {
     if (!dojo.hasClass(item, '_fixTabs')) {
     // mark item as "fixed" to prevent further fixing
     dojo.addClass(item, '_fixTabs')
     var old = item.onkeypress;
     item.onkeypress = function(ev) {
     var dir = 0;
     if (ev.keyCode==9) { // determine direction
     dir = ((ev.shiftKey==1) ? -1 : 1);
     }
     if (dir !=0) {
     var index = inputs.indexOf(item);
     if (index != -1) {
     var next = index+dir;
     //wrap around
     if (next>=inputs.length || next<0) {
     next += dir*inputs.length;
     }
     inputs[next].focus();
     }
     }
     if (old) {
     old(ev); //call old handler
     }
     }
     }
     });*/
    inputs[0].focus();
}

/****** actions ******/
function LoadActionData(form, controller, action){
    var params = dojo.formToObject(form);
    params.action = action;
    var extra = {
        postLoad: function(){
            LoadData("ProfileDataController.do", "profile", null, null);
            loadSystemData();
            //	    	if (actionDataPostLoad) {
            //	    		actionDataPostLoad();
            //            }
        }
    }
    LoadData(controller, "content", params, extra, true);
}

function confirmAction(form, controller, action, strAlert){
    var params = dojo.formToObject(form);
    params.action = action;
    popUpDialog('alert', strAlert, jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], "LoadActionData('" + form + "', '" + controller + "', '" + action + "')");
}

function confirmActionList(form, controller, action, strNoItem, strAlert){
    var params = dojo.formToObject(form);
    if (!params.checkedItems || params.checkedItems < 1) {
        popUpDialog('notice', strNoItem, jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], null);
    }
    else {
        confirmAction(form, controller, action, strAlert);
    }
}

function SortField(sortKey, ContactsDataUri, sortDirection){
    //return false;
    if (sortDirection == "down") {
        sortDirection = "up";
    }
    else {
        sortDirection = "down";
    }
    var params = {
        "sortKey": sortKey,
        "sortDirection": sortDirection,
        "action": "getSortedItems",
        "category": dojo.byId("itemsForm").category.value
    };
    LoadData(ContactsDataUri, "content", params, null, true);
}

function loadSystemData(){
    var extra = {
        postLoad: function(){
            popSystemMessage()
        }
    };
    LoadData("DataDataController.do", "data", null, extra);
}

function onLoad(){
    var focusList = dojo.query('input.jFocusFirst,select.jFocusFirst');
    if (focusList.length > 0) {
        focusList[0].focus();
    }
}

var flashHidden = false;
var flashID;
function hideFlash(){
    var obj;
    if (dojo.byId('video_obj')) {
        obj = dojo.byId('video_obj');
        if (obj && obj.offsetLeft >= 0) {
            obj.style.left = '-10000px';
            flashHidden = true;
            flashID = 'video';
        }
    }
    if (dojo.byId('audioPlayerConteiner')) {
        obj = dojo.byId('audioPlayerConteiner');
        if (obj && obj.offsetLeft >= 0) {
            obj.style.left = '-10000px';
            flashHidden = true;
            flashID = 'audio';
        }
    }
}

function showFlash(id){
    var obj;
    if (dojo.byId('video_obj')) {
        obj = dojo.byId('video_obj');
        if (obj && ((flashHidden && flashID == 'video') || id == 'video') && currentPage == 'videos') {
            obj.style.left = '0px';
            obj.style.top = '0px';
            flashHidden = false;
            flashID = '';
        }
    }
    if (dojo.byId('audioPlayerConteiner')) {
        obj = dojo.byId('audioPlayerConteiner');
        if (obj && ((flashHidden && flashID == 'audio') || id == 'audio') && currentPage == 'audios') {
            obj.style.left = '260px';
            flashHidden = false;
        }
        
    }
}

function versionIE(){
    return (navigator.appName == 'Microsoft Internet Explorer') ? parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]) : -1;
}

function isEmailValid(strEmail){
    var filter = /^.*[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}.*$/;
    if (!filter.test(strEmail)) {
        return false;
    }
    else {
        return true;
    }
}

function removeActions(){
    dojo.query(".COSDisabled").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled .clickable").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled .actionButton").forEach(function(item){
        item.parentNode.onclick = null;
        item.parentNode.onmouseover = null;
    });
    dojo.query(".COSDisabled a").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled .mid_button").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled .STWPlugin").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled .rbSummaryLink").forEach(function(item){
        item.onclick = null;
        item.onmouseover = null;
    });
    dojo.query(".COSDisabled input").forEach(function(item){
        item.disabled = true;
    });
    dojo.query(".COSDisabled select").forEach(function(item){
		var node = document.createElement('INPUT');
		node.className = item.className;
		node.id = item.id;
		node.disabled = true;
        item.parentNode.replaceChild(node,item);
    });
}

function getInputType(obj){
    for (var i = 0; i < obj.attributes.length; i++) {
        if (obj.attributes[i].nodeName == 'type') {
            return obj.attributes[i].nodeValue;
        }
    }
    return null;
}

function reloadPage(){
    window.location = 'HomePageController.do' + '?r=' + Math.random() + window.location.hash;
}

function runPostLoadAction(){
    if (commonJson && commonJson.postLoad) {
        for (id in commonJson.postLoad) {
            if (commonJson.postLoad[id].methodName && postLoadAPI[commonJson.postLoad[id].methodName]) {
                postLoadAPI[commonJson.postLoad[id].methodName](commonJson.postLoad[id].params);
            }
        }
    }
}

var postLoadAPI = {
    displayMessage: function(params){
        popUpDialog(params.type, params.message, params.title, params.func);
    }
}

function cutStringToLength(str, length){
    if (length < 3 || str == null) {
        return null;
    }
    if (str.length > length) {
        return str.substr(0, length - 3) + "...";
    }
    else {
        return str;
    }
}

function fieldsValidation(arrCheckItems){
	var objToAlert = '';
    if(arrCheckItems || typeof(arrCheckItems)=='object'){
        for (index in arrCheckItems) {
           var el = dojo.byId(arrCheckItems[index].id);
		   for(typeIndex in arrCheckItems[index].checks){
		   	  var check = arrCheckItems[index].checks[typeIndex];
		   	  switch(check['type']){
			  	case 'isNotEmpty':
				    if (!(el && el.value)) {
		              objToAlert = {
					  	item: arrCheckItems[index],
						type: check['type']
					  }
		            }
				    break;
				case 'email':
				    if (el && validateEmail(el.value)) {
                      objToAlert = {
                        item: arrCheckItems[index],
                        type: check['type']
                      }
					}
					break;
				default:
				   objToAlert = ''; 
			  }
			  if (typeof(objToAlert)=='object'){
			  	  var strMessage = getMessage(objToAlert.item.checks,objToAlert.type);
				  strMessage = strMessage.replace(/%name%/, objToAlert.item.name);
				  popUpDialog('notice', strMessage , 'Attention!!!','fieldFocus(' +"'" + objToAlert.item.id + "'" + ')');
				  return false;
			  } 
		   }
       }
        return true;
    }else{
        return false;
    }
}

function validateEmail (str) {
    return str.match(/^\b[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z0-9._%-]{2,4}\b$/);
}

function validatePhone(str) {
    return str.match(/^[0-9pw+\-*#]+$/);
}

function getMessage(arrChecks, type){
	for (index in arrChecks){
		if (arrChecks[index].type == type){
			return arrChecks[index].message;
		}
	}
}

function fieldFocus(strFieldId){
	var el = dojo.byId(strFieldId);
	if (el){
		el.focus();
	}
	return false;
}

function blockEnter(event,fireObjId){
	if(event.keyCode == 13){
		if(fireObjId && dojo.byId(fireObjId)){
            dojo.byId(fireObjId).onclick();
		}
		return false;
	}
}
var DP = new DPO();
function DPO(){
    this.d = new Date();
    this.startYear;
    this.endYear;
    this.currentMonth;
    this.currentYear;
    this.currentDay;
    this.currentSOM;
    this.currentNOD;
    this.targetId;
    this.calendarConteiner;
    this.calendarConteinerID;
    this.arrDate;
    this.topTuning = 0;
    this.leftTuning = 0;
    //Note that first day of week should generally be obtained from user preferences, and not be hard coded
    this.firstDayOfWeek = 1;
    this.datePicker = function(targetId, startYear, endYear, topTuning, leftTuning, sourceID, firstDayOfWeek, noDelete){
        if (noDelete) {
            dojo.byId("DPEmptyDate").style.display = 'none';
        }
        else {
            dojo.byId("DPEmptyDate").style.display = 'block';
        }
        if (firstDayOfWeek) {
            this.firstDayOfWeek = firstDayOfWeek;
        }
        if (!endYear) {
            var cd = new Date();
            endYear = cd.getFullYear();
        }
        list = dojo.query('.datePickerClose').forEach(function(obj){
            if (obj.onclick) {
                obj.onclick();
            }
        });
        if (topTuning) {
            this.topTuning = topTuning;
        }
        if (leftTuning) {
            this.leftTuning = leftTuning;
        }
        this.startYear = startYear;
        this.endYear = endYear;
        this.targetId = targetId;
        if (sourceID != null) {
            this.calendarConteinerID = sourceID;
        }
        else {
            this.calendarConteinerID = this.targetId + '_datePicker';
        }
        var strDate = dojo.byId(targetId).value;
        if (strDate.length > 0) {
            this.arrDate = strDate.split('/');
            this.arrDate[0]--;
            this.d = new Date(this.arrDate[2], this.arrDate[0], this.arrDate[1]);
        }
        else {
            this.d = new Date();
            this.arrDate = new Array(this.d.getMonth(), this.d.getDate(), this.d.getFullYear());
        }
        this.prepareCanvas();
        this.buildMonth();
    }
    this.prepareCanvas = function(){
        var invoker = dojo.byId(this.targetId);
        this.calendarConteiner = dojo.byId(this.calendarConteinerID);
        var parent = invoker.parentNode;
        var top = invoker.offsetTop + this.topTuning;
        var left = invoker.offsetLeft + this.leftTuning;
        this.calendarConteiner.innerHTML = '';
        this.calendarConteiner.className = 'datePickerConteiner';
        this.calendarConteiner.style.top = top + 'px';
        this.calendarConteiner.style.left = left + 'px';
        this.calendarConteiner.style.display = 'block';
        this.calendarConteiner.innerHTML = dojo.byId('datePicker').innerHTML;
        var selectsConteiner = dojo.query(".datePickerSelects", this.calendarConteiner)[0];
        var selectYear = dojo.query("select.datePickerYear", selectsConteiner)[0];
        var selectMonth = dojo.query("select.datePickerMonth", selectsConteiner)[0];
        
        while (selectYear.options.length > 0) {
            selectYear.removeChild(selectYear.options[0]);
        }
        for (var y = this.startYear; y <= this.endYear; y++) {
            this.createOption(selectYear, y, y);
        }
        if (this.arrDate) {
            selectMonth.options[this.arrDate[0]].selected = true;
        }
        if (dojo.isIE < 7) {
            this.calendarConteiner.appendChild(document.createElement("iframe"));
        }
        var targetId = this.targetId;
        var calendarConteiner = this.calendarConteiner;
        var objClose = dojo.query('.datePickerClose', this.calendarConteiner)[0];
        objClose.onclick = function(){
            document.body.onclick = null;
            calendarConteiner.style.display = 'none';
            calendarConteiner.innerHTML = '';
            if (dojo.byId(targetId) && // when it was the parent's closing that triggers this
            dojo.byId(targetId).onchange &&
            typeof(dojo.byId(targetId).onchange) == 'function') {
                dojo.byId(targetId).onchange();
            }
            objClose.onclick = '';
        };
        setTimeout(function(){
            document.body.onclick = function(evt){
                if (!is_child_of(calendarConteiner, getEventTarget(evt))) {
                    objClose.onclick();
                }
            };
        }, 100);
        dojo.query('.datePickerSelects .empty', this.calendarConteiner)[0].onclick = function(){
            this.onclick = '';
            dojo.byId(targetId).value = '';
            objClose.onclick();
        }
    }
    this.calculateMonth = function(){
        this.currentMonth = this.d.getMonth();
        this.currentYear = this.d.getFullYear();
        this.currentDay = this.d.getDate();
        this.d.setDate(1)
        this.currentSOM = this.d.getDay();
        this.currentSOM -= this.firstDayOfWeek;
        if (this.currentSOM < 0) {
            this.currentSOM += 7;
        }
        this.d.setMonth(this.currentMonth + 1);
        this.d.setDate(0);
        this.currentNOD = this.d.getDate();
    }
    this.buildMonth = function(){
        this.calculateMonth();
        var days = dojo.query('.datePickerDayEmpty, .datePickerDay, .datePickerDayVacation', this.calendarConteiner).orphan();
        var dayCounter = 0;
        for (var i = 0; i < 6; i++) {
            for (var j = 1; j < 8; j++) {
                var currentDayO = this.createDay();
                this.calendarConteiner.appendChild(currentDayO);
                if (i == 0) {
                    if (j <= this.currentSOM) {
                        currentDayO.className = 'datePickerDayEmpty';
                        continue;
                    }
                }
                else {
                    if (dayCounter >= this.currentNOD) {
                        currentDayO.className = 'datePickerDayEmpty';
                        continue;
                    }
                }
                dayCounter++;
                if (j == 7) {
                    currentDayO.className = 'datePickerDayVacation';
                }
                if (this.arrDate) {
                    if (dayCounter == this.currentDay && this.currentYear == this.arrDate[2] && this.currentMonth == this.arrDate[0]) {
                        currentDayO.style.fontWeight = 'bold';
                    }
                }
                currentDayO.innerHTML = dayCounter;
                var currentYear = this.currentYear;
                var currentMonth = this.currentMonth;
                var targetId = this.targetId;
                var calendarConteiner = this.calendarConteiner;
                var objClose = dojo.query('.datePickerClose', this.calendarConteiner)[0];
                currentDayO.onclick = function(){
                    var target = dojo.byId(targetId);
                    var strResult = ((currentMonth + 1) + '/' + this.innerHTML + '/' + currentYear);
                    target.value = strResult;
                    //dojo.byId('birthDay').value = strResult;
                    //alert(calendarConteiner);
                    //alert(calendarConteiner.id);
                    objClose.onclick();
                }
            }
        }
    }
    this.createDay = function(){
        var day = document.createElement('DIV');
        day.className = 'datePickerDay';
        return day;
    }
    
    this.setYearValue = function(year){
        this.currentYear = year;
        this.d = new Date(this.currentYear, this.currentMonth, this.currentDay);
        this.buildMonth();
    }
    this.setMonthValue = function(month){
        this.currentMonth = month;
        this.d = new Date(this.currentYear, this.currentMonth, this.currentDay);
        this.buildMonth();
    }
    this.createOption = function(parent, value, name){
        var option = document.createElement('option');
        option.value = value;
        option.text = name;
        if (this.arrDate) {
            if (value == this.arrDate[2]) {
				option.selected = true;
			}
        }
        parent.options[parent.options.length] = option;
    }
}
var contactRowHeight=0;

function loadContacts(params){

    var extra = {
        postLoad: function(){
            strObject = dojo.byId('contactsFilter').value;
            
            if (strObject.length > 0) {
                ContactsFilter = eval('(' + strObject + ')');
            }
            currentPage = 'contacts';
			var rows = dojo.query("#contacts .list .row:nth-child(2)");
			if (rows && rows.length > 0) {
				contactRowHeight =  rows[0].offsetHeight;
			}			
            hideFlash();
	        if (dojo.query("#contacts .GOOGLE_CONTACTS.pluginIsFirstTime")[0].innerHTML == "true") {
                popUpDialog('alert', jsLocaleBundle['JS.SETTINGS.SECTIONS.GOOGLE_CONTACTS.DO_YOU_WANT_TO_SYNC_ONLY_WITH_PHONES'], jsLocaleBundle['JS.POPUP.TITLE.ATTENTION'], 'googleSyncContacts(true)', true,'googleSyncContacts(false)');
			}
			else {
				loadSystemData();
			}
        }
    };
    LoadData('ContactsDataController.do', 'content', params, extra, null, 'loadContacts');
}


function loadContact(id){
    var params = {
        action: 'load',
        VCardId: id
    };
    LoadHtmlToPopup("ContactsEditController.do", params, 
	   jsLocaleBundle[(id==0)?"JS.ADD_CONTACTS.ADD.TITLE":"JS.ADD_CONTACTS.EDIT.TITLE"], 
	   null);   
    takeValuesToMain();
    setTimeout(loadContactPics, 1000);
}

// "off" if true turns any previous highlighting ans status msg off
// return true if check was done and failed
function mandatoryFieldsCheck(off){
    // assoc. array with the optional value containg the corresponding validation function
    var mustFields = ["phone", "email", "firstName", "lastName"];
    var mustValidators = {
        "phone": "",
        "email": validateEmail,
        "firstName": "",
        "lastName": ""
    };
    
    if (off) {
        dojo.forEach(mustFields, function(item){
            if (!dojo.byId("main_" + item).readOnly) {
                dojo.style(dojo.byId("main_" + item), "backgroundColor", "");
            }
        })
        dojo.query("#editContact .status").style({
            visibility: "hidden"
        });
    }
    else 
        if (dojo.every(mustFields, function(item){
            var str = dojo.byId("main_" + item).value;
            return str == "" || (mustValidators[item] && typeof(mustValidators[item]) == 'function' && !mustValidators[item](str)); // empty or invalid
        })) {
            dojo.forEach(mustFields, function(item){
                dojo.style(dojo.byId("main_" + item), "backgroundColor", "yellow");
            })
            dojo.query("#editContact .status")[0].innerHTML = jsLocaleBundle["JS.SAVE_CONTACT.MUST_FIELDS.MSG"];
            dojo.query("#editContact .status").style({
                visibility: "visible",
                color: "red"
            });
            return true;
        }
    return false;
}

function enableAllPhoneTypes(){
    var phoneTypes = document.getElementsByName('phoneType');
    var i = 0;
    for (i = 0; i < phoneTypes.length; i++) {
        phoneTypes[i].disabled = false;
    }
    return dojo.byId("saveContactForm");
}

function saveContact(self){
    if (mandatoryFieldsCheck()) {
        return;
    }
    if (!checkContactEmails()) {
        return;
    }
    dojo.require("dojo.io.iframe");
    dojo.io.iframe.send({
        method: "post",
        form: enableAllPhoneTypes(),
        handleAs: "html",
        handle: function(response, ioArgs){
            if (response instanceof Error) {
                //console.debug("Request FAILED: ", response);
            }
            else {
                AjaxParse(response.body.innerHTML, function(){
                    if (commonJson.messageToDisplay) {
                        popUpDialog('notice', commonJson.messageToDisplay, 'Attention');
                    }
                    if (commonJson.errorType) {
                        popUpDialog('notice', commonJson.errorMessage, 'Error');
                    }
                });
                if (self) {
                    LoadData("ProfileDataController.do", "profile", null, null);
                }
                else {
                    if (currentPage == 'home') {
                        loadHome();
						loadSystemData();
                    }
                    else {
                        loadContacts();
                    }
                }
            }
            ioResponse = response;
        }
    });
    var phoneTypes = document.getElementsByName('phoneType');
    var i = 0;
    for (i = 0; i < phoneTypes.length; i++) {
        phoneTypes[i].disabled = false;
    }
    closePopUp();
}

function FilterContacts(){
    if (!ContactsFilter) {
        strObject = dojo.byId('contactsFilter').value;
        ContactsFilter = eval('(' + strObject + ')');
    }
    value = dojo.byId('contactsFilterField').value.toLowerCase();
    for (i in ContactsFilter) {
        row = dojo.byId('contact_' + ContactsFilter[i].ID)
        if (ContactsFilter[i].FilterString.toLowerCase().indexOf(value) >= 0) {
			if(dojo.hasClass(row,'hidden')){
				dojo.removeClass(row,'hidden');
			}
        }
        else {
            if(!dojo.hasClass(row,'hidden')){
                dojo.addClass(row,'hidden');
            }
        }
    }
    dojo.query('.filtering .progress').addClass = 'invisible';
}

function addContactSetCurrentTab(id){
    dojo.query("#editContact .tab").style("display", "none");
    dojo.query("#editContact .tabs .label").removeClass("active");
    dojo.byId('tab_ec_' + id).style.display = 'block';
    try {
        fixInputFocus('#tab_ec_' + id + ' .all_inputs');
    } 
    catch (e) {
    
    }
    dojo.addClass(dojo.byId('tab_label_ec_' + id), 'active');
    if (id == 'main') {
        takeValuesToMain();
    }
    mandatoryFieldsCheck("off");
}

var lastSElectedPic;
function setPicFromGallery(obj){
    if (lastSElectedPic) {
        //lastSElectedPic.parentNode.style.border = '1px solid silver';
    }
    //obj.parentNode.style.border = '1px solid orange';
    lastSElectedPic = obj;
    dojo.byId('contact_picture_pic_img').src = obj.src;
    dojo.byId('contact_main_pic_img').src = obj.src;
    dojo.byId('contactPicID').value = obj.id;
    dojo.byId('pic_type_gallery').checked = true;
}

function takeValuesToMain(){
    copyValue('firstName', 'main_firstName');
    copyValue('lastName', 'main_lastName');
    copyValue('birthDay', 'main_birthDay');
    updatePrefPhoneBack();
    copyValue('email1', 'main_email');
    copyValue('addressStreet1', 'main_street');
    copyValue('addressCity1', 'main_city');
    copyValue('addressZip1', 'main_zip');
    copyValue('addressCountry1', 'main_country');
}

function updatePrefPhone(){
    for (var i = 1; i < 10; i++) {
        if (dojo.byId('phonePrefId' + i) && dojo.byId('phonePrefId' + i).checked) {
            dojo.byId('phone' + i).value = dojo.byId('main_phone').value;
            if (dojo.byId('main_phoneType').selectedIndex != null) {
                dojo.byId('phoneType' + i).selectedIndex = dojo.byId('main_phoneType').selectedIndex;
            }
            return true;
        }
    }
    dojo.byId('phone1').value = dojo.byId('main_phone').value;
    dojo.byId('phoneType1').selectedIndex = dojo.byId('main_phoneType').selectedIndex;
    return true;
}

function updatePrefPhoneBack(){
    var valueTaken = false;
    var objPhone, objSelect, value = "";
    for (var i = 1; i < 10; i++) {
        if (dojo.byId('phonePrefId' + i) && dojo.byId('phonePrefId' + i).checked) {
            objPhone = dojo.byId('phone' + i);
            value = objPhone.value;
            objSelect = dojo.byId('phoneType' + i);
            valueTaken = true;
        }
    }
    if (valueTaken == false) {
        for (var i = 1; i < 10; i++) {
            if (dojo.byId('phone' + i) && dojo.byId('phone' + i).value.length > 0) {
                objPhone = dojo.byId('phone' + i);
                value = objPhone.value;
                objSelect = dojo.byId('phoneType' + i);
                valueTaken = true;
            }
        }
    }
    if (valueTaken == false) {
        objPhone = dojo.byId('phone1');
        value = (objPhone ? objPhone.value : "");
        objSelect = dojo.byId('phoneType1');
    }
    dojo.byId('main_phoneType').selectedIndex = objSelect.selectedIndex;
    
    dojo.byId('main_phone').value = value;
    if (objPhone.readOnly) {
        dojo.byId('main_phone').readOnly = true;
    }
    if (objSelect.disable) {
        dojo.byId('main_phoneType').disable = true;
    }
    if (objPhone.style.backgroundColor) {
        dojo.byId('main_phone').style.backgroundColor = objPhone.style.backgroundColor;
    }
    return true;
}

function SortContacts(sortKey, ContactsDataUri, sortDirection){
    var params = {
        "sortKey": sortKey,
        "sortDirection": ((sortDirection == "down") ? "up" : "down"), // reverse direction
        "action": "getSortedContacts"
    };
    LoadData(ContactsDataUri, "content", params, null, true);
}

function loadContactsAndScroll(coord){
    var post = {
        "sortKey": 'name',
        "sortDirection": 'down',
        "action": "getSortedContacts"
    };
    extra = {
        coord: coord,
        postLoad: function(){
            ScrollTo('#contacts .scroller', this.coord);
        }
    }
    LoadData('ContactsDataController.do', 'content', post, extra, true);
}

function preDeleteCheckedContacts(strNoItem, strAlert){
    var params = dojo.formToObject("contactsForm");
    if (!params.checkedContacts || params.checkedContacts < 1) {
        popUpDialog('notice', strNoItem, 'Confirm', null);
    }
    else {
        popUpDialog('alert', strAlert, 'Confirm', 'deleteCheckedContacts()');
    }
}

function contactToolTip(id){
    popUpDialog('tooltip', '<img src="ImageController.do?contactID=' + id + '&operation=bigContactThumb&rn=' + Math.random() + '" alt="" />');
}

function deleteCheckedContacts(){
    var params = dojo.formToObject("contactsForm");
    params.action = "deleteContacts";
    loadContacts(params);
}

function loadContactPics(){
    var x = 15;
    try {
        fixInputFocus('#tab_ec_main .all_inputs');
    } 
    catch (e) {
    }
    var nodes = dojo.query("#tab_ec_picture .picFromGallery img[src]");
    dojo.query("#tab_ec_picture .picFromGallery img[src='']").slice(0, x - 1).forEach(function(img){
        dojo.attr(img, "src", "ImageController.do?fileID=" + img.id + "&operation=galleryPhotoThumbForContact");
        img.parentNode.style.display = 'block';
    });
}

var contactPicScroller;
function checkAddContactPicScroll(obj){
    contactPicScroller = obj;
    var height = obj.scrollHeight;
    var scrolled = obj.scrollTop + obj.offsetHeight;
    if (height / 3 * 2 < scrolled) {
        loadContactPics();
    }
}

function checkContactEmails(){
    var stopper = false;
    var queryString = "input[type='text'][name='email']";
    var list = dojo.query(queryString);
    list.forEach(function(item){
        dojo.removeClass(item, 'inputAttention');
    });
    list.forEach(function(item){
        if (item.value.length > 0 && !isEmailValid(item.value)) {
            addContactSetCurrentTab('internet');
            dojo.addClass(item, 'inputAttention');
            dojo.query("#editContact .status")[0].innerHTML = jsLocaleBundle["JS.SAVE_CONTACT.EMAIL_NOT_VALID.MSG"];
            dojo.query("#editContact .status").style({
                visibility: "visible",
                color: "red"
            });
            stopper = true;
        }
    });
    if (stopper) {
        return false;
    }
    else {
        return true;
    }
}

function googleSyncContacts(withPhones){
	var swp = 0;
	if(withPhones == true){
		swp = 1;
	}else if(withPhones == false){
		swp = 2;
	}
    var post = {
        action: "googleSync",
		syncOnlyWithPhones:swp
    };
	var objMessage = dojo.query('#sidebar_info .synced')[0];
    if (objMessage.style.color == 'red') {
        return;
    }
    objMessage.innerHTML = jsLocaleBundle["JS.CONTACTS.GOOGLE_SYNC_IN_PROGRESS"];
    objMessage.style.color = 'red';
    objMessage.style.fontWeight = "bold";
	dojo.query("#GOOGLE_CONTACTSform .button").style('display','none');
    var extra = {
        postLoad: function(){
			dojo.query("#GOOGLE_CONTACTSform .button").style('display','block');
			if (currentPage == 'contacts') {
				loadContacts();
			} else {
                loadSystemData();
			}
			 
        }
    }    
    LoadData('ContactsDataController.do', null, post, extra, true);
}
function loadSearch(){
	    var extra = {
        postLoad: function(){
            currentPage = 'search';
            hideFlash();
        }
    }; 
	var strSearchKey = dojo.byId('globalSearchKey').value;
	var params = {
		action :'search',
		searchKey : strSearchKey
	}  ;
    LoadData('GlobalSearchController.do', 'content',params,extra,null,'loadSearch');
}
function loadRecycleBin(){
    var extra = {
        postLoad: function(){
            currentPage = 'recycleBin';
            hideFlash();
        }
    };
    LoadData('RecycleDataController.do', 'content', null, extra, null, 'loadRecycleBin');
}

function recycleBin_category(name){
    extra = {
        postLoad: function(){
            hideFlash();
        }
    }
    uri = "RecycleDataController.do";
    target = "content";
    var post = dojo.formToObject(dojo.byId('itemsForm'));
    post.action = 'loadCategory';
    post.category = name;
    LoadData(uri, target, post, extra, null, 'recycleBin_category-' + name);
}

var actionDataPostLoad;
function purgeCheckedItems(strNoItem, strAlert){
    actionDataPostLoad = function(){
        LoadData("ProfileDataController.do", "profile", null, null);
    }
    confirmActionList("itemsForm", "RecycleDataController.do", "purgeItem", strNoItem, strAlert);
}

function restoreCheckedItems(strNoItem, strAlert){
    confirmActionList("itemsForm", "RecycleDataController.do", "restoreItem", strNoItem, strAlert);
}

function purgeAllItems(strAlert){
    actionDataPostLoad = function(){
        LoadData("ProfileDataController.do", "profile", null, null);
    }   
    confirmAction("itemsForm", "RecycleDataController.do", "purgeAll", strAlert)
}


function loadMessages(){ 
	var extra = {
        postLoad: function(){
            currentPage = 'messages';
            hideFlash();
        }
    }; 
	
    LoadData('MessagesDataController.do', 'content',null,extra,null,'loadMessages');
}

function messagesNextPage(){
    var params = dojo.formToObject("messagesPagingForm");
    params.action = "next";
    params.pageNum = 0;
    var controller = "MessagesDataController.do";
    LoadData(controller, "content", params, null, true);
}

function messagesPrevPage(){
    var params = dojo.formToObject("messagesPagingForm");
    params.action = "prev";
    params.pageNum = 0;
    var controller = "MessagesDataController.do";
    LoadData(controller, "content", params, null, true);
}

function messagesNumPage(num){
    var params = dojo.formToObject("messagesPagingForm");
    params.action = "pageByNum";
    params.pageNum = num;
    var controller = "MessagesDataController.do";
    LoadData(controller, "content", params, null, true);
}

function SortMessages(sortKey, ContactsDataUri, sortDirection){
    //return false;
    if (sortDirection == "down") {
        sortDirection = "up";
    }
    else {
        sortDirection = "down";
    }
    var params = {
        "sortKey": sortKey,
        "sortDirection": sortDirection,
        "action": "getSortedItems"
    };
    LoadData(ContactsDataUri, "content", params , null , true);
}

function sendMessageContactClick(e) {
	if (getAncestorWithClass(e.target, "potentials")) {
		// only the "potentials" contacts can be folded
        if (dojo.hasClass(e.target, "contact")) {
            if (!dojo.query(".folding", e.target).hasClass("expanded")) {
                // only one expanded name at a time, and this one is the old one
                
                var nodes = dojo.query("#sendMessage .potentials .folding.expanded");
                if (nodes.length >0) { // got the node, so hide it
                    nodes[0].removeClass("expanded");
                    dojo.query(".items", getAncestorWithClass(nodes[0], "contact")).addClass("hidden");
                 }
            }
            
            //visualize and (un)hide
            dojo.query(".folding", e.target).toggleClass("expanded");
            dojo.query(".items", e.target).toggleClass("hidden");
        } 
		
        if (dojo.hasClass(e.target, "item")) {
            // adding contact/item (from the left to right)
			
			if (!dojo.byId(e.target.id.replace(/potential/, "target"))) { 
                // item not already present in target
				var contact = getAncestorWithClass(e.target, "contact");
				var targetContact = dojo.byId(contact.id.replace(/potential/, "target")) 
				if (!targetContact) {
				    // contact not present in target, so clone it, modify and add
					// the user can't click an item in a folded contact so we can assume it's open 
					targetContact = contact.cloneNode(true);
					dojo.query(".item", targetContact).orphan();
					targetContact.id = targetContact.id.replace(/potential/, "target");
					dojo.removeClass(targetContact, "clickable")
					dojo.query("#sendMessage .targets .list")[0].appendChild(targetContact); 
				}
				var target = e.target.cloneNode(true);
				target.id = target.id.replace(/potential/, "target");
				dojo.removeClass(target, "addItem");
                dojo.addClass(target, "delete");
				
				dojo.query(".items", targetContact)[0].appendChild(target);

                dojo.addClass(e.target, "disabled");
                dojo.addClass(contact, "marked");
			}
		}
	} else if (getAncestorWithClass(e.target, "targets")) {
		if (dojo.hasClass(e.target, "item")) {
            dojo.removeClass(dojo.byId(e.target.id.replace(/target/, "potential")), "disabled")
			
			var contact = getAncestorWithClass(e.target, "contact");
			e.target.parentNode.removeChild(e.target);
			if (dojo.query(".items", contact).length == 0) {
				contact.parentNode.removeChild(contact);
			}
		}
	}
}

function messagesSearch(){
	if(document.getElementById('searchKey').value.length < 3){
		popUpDialog('notice', jsLocaleBundle['JS.MESSAGES.SEARCH.KEY_TOO_SHORT'],jsLocaleBundle['JS.POPUP.TITLE.ATTENTION']);
		return;
	}
    uri = "MessagesDataController.do";
    target = "content";
    var post = dojo.formToObject(dojo.query('#messages form.search')[0]);
    post.action = 'search';
    LoadData(uri, target, post, null, true);
}
function messagesSearchClear(){
    uri = "MessagesDataController.do";
    target = "content";
    var post = {
		action: 'clearSearch'
	};
    LoadData(uri, target, post, null, true);	
}
var galleryPageToReload;
function addFilePopUp(title, page){
    galleryPageToReload = page;
    //hideFlash();
    LoadHtmlToAddFilePopup("FileUploadController.do", null, title, null);
}


function uploadFile(){
    var controller;
    switch (galleryPageToReload) {
        case "audios":
            controller = "AudiosDataController.do";
            break;
        case "photos":
            controller = "PhotosDataController.do";
            break;
        case "videos":
            controller = "VideosDataController.do";
			break;
		case "documents":
            controller = "DocumentsDataController.do";
            break;
    }
    dojo.query("#fileUpload input.fileUploadSource").filter(function(item){ return (item.value ==''); }).orphan();
	var fileList = dojo.query("#fileUpload input.fileUploadSource");
	if (fileList.length < 1 ) {
		popUpDialog('notice', jsLocaleBundle["JS.FILE_UPLOAD.NO_FILES.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
		return;
	}
	fileList.forEach(function(item, index, arr){
		item.name = item.name.replace(/\d+/, index);
	});

    var h = dojo.byId('fileUploadConteinerText').offsetHeight;
    dojo.byId('fileUploadConteiner').style.display = 'none';
    dojo.byId('fileUploadMessage').style.display = 'block';
    dojo.require("dojo.io.iframe");
    dojo.io.iframe.send({
        method: "post",
        form: dojo.byId("fileUpload"),
        handleAs: "html",
        handle: function(response, ioArgs){
            if (response instanceof Error) {
                dojo.byId('fileUploadMessage').innerHTML = response.body.textContent;
            }
            else {
                var responseMessage;
            	AjaxParse(response.body.innerHTML, function(){
	                if (commonJson.messageToDisplay) {
                        responseMessage = commonJson.messageToDisplay;
                            }
	                if (commonJson.errorType) {
                        responseMessage = commonJson.errorMessage;
                    }
	            });

                if (responseMessage) {
                    dojo.byId('fileUploadMessage').innerHTML = responseMessage;
                    dojo.byId('fileUploadMessage').style.height = h + 'px';
                    dojo.byId('fileUploadMessageButton').style.display = 'block';
                }
                else {
                    closePopUp();
                }
            }
            ioResponse = response;
            LoadData(controller, "content", null);
			LoadData("ProfileDataController.do", "profile", null, null);
        }
    });

}

function addFileRow(){
	var maxFileSlots = 6;
    var count = parseInt(dojo.byId('fCount').value);
	if (count >= maxFileSlots) {
		return;
	}
    var field = document.createElement('INPUT');
    field.type = 'FILE';
    field.className = 'fileUploadSource';
    field.name = 'fileToUploadList[' + count + ']';
    dojo.byId('fileUpload').appendChild(field);
	count++;
    dojo.byId('fCount').value = count;
  	if(count >= maxFileSlots){
	   dojo.byId('moreFiles').style.display = 'none';
	   dojo.addClass(dojo.byId("moreFiles"), "disabled");
	}
	dojo.byId('backdrop').style.height = dojo.byId('overDiv').offsetHeight + 'px';
	dojo.byId('backdrop').style.clip = '';
}

function loadPhotos(){
    var extra = {
        postLoad: function(){
            currentPage = 'photos';
            hideFlash();
        }
    };
    LoadData('PhotosDataController.do', 'content', null, extra, null, 'loadPhotos');
}

function photosNextPage(){
    var params = dojo.formToObject("photosPagingForm");
    params.action = "next";
    params.pageNum = 0;
    var controller = "PhotosDataController.do";
    LoadData(controller, "content", params, null, true);
}

function photosPrevPage(){
    var params = dojo.formToObject("photosPagingForm");
    params.action = "prev";
    params.pageNum = 0;
    var controller = "PhotosDataController.do";
    LoadData(controller, "content", params, null, true);
}

function photosNumPage(num){
    var params = dojo.formToObject("photosPagingForm");
    params.action = "pageByNum";
    params.pageNum = num;
    var controller = "PhotosDataController.do";
    LoadData(controller, "content", params, null, true);
}

function photosOpen(id){
    if (isNaN(id)) {
        id = 0;
    }
    var params = {
        photoID: id,
        action: "load"
    };
    var controller = "PhotosEditController.do";
    var extra = {
        postLoad: function(){
            if (commonJson) {
                img_ids = commonJson.ids;
                img_cur = commonJson.current;
                img_size = commonJson.size;
            }
			if(versionIE() == 6){
				var img = dojo.query('#p3 img')[0];
				dojo.attr(img, "src", "ImageController.do?fileID=" + id + "&operation=galleryPhotoView");
				dojo.byId('view_photo_frame').style.border = 0;
			}else{
                editPhotoInit();
			}
            editPhotoApplyState(getCurEditPhotoNode());
            dojo.byId('imageName' + id).innerHTML = dojo.byId('currentFileName').value;
        }
    }
    LoadData(controller, "content", params, extra, null, 'photosOpen-' + id);
}

function videosOpen(id){
    if (isNaN(id)) {
        id = 0;
    }
    var params = {
        videoID: id,
        action: "load"
    };
    var controller = "VideosEditController.do";
    var extra = {
        postLoad: function(){
            if (id > 0 && dojo.byId('flash_url')) {
                startFlashVideo(dojo.byId('flash_url').value);
            }
            else {
                startFlashVideo(null);
            }
        }
    };

    LoadData(controller, "edit_video", params, extra);
}

function loadVideos(id){
    if (!id || isNaN(id)) {
        id = 0;
    }
    var params;
    if (id) {
        params = {
            currentItem: id,
            action: 'openItem'
        };
    }
    else {
        params = null;
    }
    var extra = {
        postLoad: function(){
            currentPage = 'videos';
            hideFlash();
            showFlash('video');
            if (id > 0 && dojo.byId('flash_url')) {
                startFlashVideo(dojo.byId('flash_url').value);
            }
            else {
                startFlashVideo(null);
            }
        }
    };
    LoadData('VideosDataController.do', 'content', params, extra, null, 'loadVideos');
}

function placeAudioPlayer(){
	if(dojo.byId('music')){
        var offset = (dojo.byId('music').offsetTop || dojo.byId('music').clientTop) + (dojo.byId('content').offsetTop || dojo.byId('content').clientTop);
        dojo.byId('audioPlayerConteiner').style.top = offset + 'px';
	}
}

function audiosOpen(id){
    var artist;
    var title;
    if (isNaN(id)) {
        id = 0;
    }
    var params = {
        audioID: id,
        action: "load"
    };
    var controller = "AudiosEditController.do";
    var extra = {
        postLoad: function(){
            wimpy_stop();
            wimpy_clearPlaylist();
            var addFiles = "";
            addFiles += "<playlist>";
            addFiles += AudioCreateWimpyPlaylistItem(id);
            addFiles += "</playlist>";
            wimpy_appendPlaylist(addFiles);
            wimpy_play();
        }
    }
    LoadData(controller, "editAudio", params, extra);
}

function AudioCreateWimpyPlaylistItem(nodeOrItemId) {
    var itemNode;
	if (typeof nodeOrItemId == "object") {
		itemNode = nodeOrItemId;
	} else if(typeof nodeOrItemId == "string" || typeof nodeOrItemId == "number") {
		itemNode = dojo.query("#music .item_" + nodeOrItemId)[0];
	}
	if (!itemNode) {
		return "";
	}
	
    artist = (itemNode ? dojo.query('.mediaArtist', itemNode)[0].innerHTML: jsLocaleBundle["JS.GENERAL.UNKNOWN"]);
    title = (itemNode ? dojo.query('.mediaTitle', itemNode)[0].innerHTML: jsLocaleBundle["JS.GENERAL.UNKNOWN"]);
    filename = (itemNode ? dojo.query('.fileUrl', itemNode)[0].innerHTML: jsLocaleBundle["JS.GENERAL.UNKNOWN"]);
    //filekind = (itemNode ? dojo.query('.filekind', itemNode)[0].innerHTML: jsLocaleBundle["JS.GENERAL.UNKNOWN"]);
	
    var addFiles = "";
    addFiles += "  <item>";
    addFiles += "    <filename>" + filename + "</filename>";
    addFiles += "    <artist>" + artist + "</artist>";
    addFiles += "    <title>" + title + "</title>";
    //addFiles += "    <filekind>" + filekind + "</filekind>";
    //addFiles += "    <link>http://www.gieson.com</link>";
    //addFiles += "    <image>example1.jpg</image>";
    addFiles += "  </item>";
	return addFiles;
}

function addCheckedItemsToPlaylist() {
    var list = dojo.query("#music .list.items input[type='checkbox'][name='item']").filter(function(item){ return item.checked;});
    if (list.length < 1 ) {
        popUpDialog('notice', jsLocaleBundle["JS.GENERAL.NO_FILES.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
        return;
	}
	
    var addFiles = "";
    addFiles += "<playlist>";
    addFiles += list.map(function(item){ return AudioCreateWimpyPlaylistItem(getAncestorWithClass(item, 'item')); }).join("");
    addFiles += "</playlist>";
    wimpy_appendPlaylist(addFiles);
}

function loadAudios(id){
    if (!id || isNaN(id)) {
        id = 0;
    }
    var params;
    if (id) {
        params = {
            currentItem: id,
            action: 'openItem'
        };
    }
    else {
        params = null;
    }
    var extra = {
        postLoad: function(){
            currentPage = 'audios';
			placeAudioPlayer();
            showFlash('audio');
            if (id && id > 0) {
                wimpy_stop();
                wimpy_clearPlaylist();
                audiosOpen(id);
            }
        }
    };

    LoadData('AudiosDataController.do', 'content', params, extra, null, 'loadAudios');
}

var galleryDeleteController;
var galleryDeleteParams;
var galleryDeleteExtra;
var countCheckedFiles;
function deleteCheckedFiles(type){
	galleryDeleteExtra = null;
    var params = dojo.formToObject("itemsForm");
    params.action = "delete";
    var controller;
    switch (type) {
        case "audios":
            controller = "AudiosDataController.do";
            break;
        case "photos":
            controller = "PhotosDataController.do";
            break;
        case "videos":
            controller = "VideosDataController.do";
			galleryDeleteExtra = {
				postLoad : function(){
					startFlashVideo(null);
				}
			};
            break;
        case "documents":
            controller = "DocumentsDataController.do";
            break;
    }
    galleryDeleteController = controller;
    galleryDeleteParams = params;
    //hideFlash();
    if (params.item && params.item.length > 0) {
   	 if(typeof(params.item)=='object'){
        popUpDialog('alert', jsLocaleBundle["JS.POPUP.ITEMS_DELETE.CONFIRM_MSG"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], 'executeDelete()');
   	  }else{
   	   popUpDialog('alert',jsLocaleBundle["JS.POPUP.ITEM_DELETE.CONFIRM_MSG"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], 'executeDelete()');
   	  }
    }
    else {
        popUpDialog('notice', jsLocaleBundle["JS.POPUP.ITEMS_DELETE.NO_ITEMS_MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], 'showFlash()');
    }
    //LoadData(controller, "content", params);
}

function uploadCheckedItems(type, STWplugin, uploadingMessage){
	if (!dojo.query(".list.items input[type='checkbox'][name='item']").some(function(item){ return item.checked; })) {
	    //hideFlash();
        popUpDialog('notice', jsLocaleBundle["JS.FILE_UPLOAD.NO_FILES.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], 'showFlash()');
		return;
	}
	
    var params = dojo.formToObject("itemsForm");
    params.action = 'upload';
    params.plugin = parseInt(STWplugin);
    var controller;
    switch (type) {
        case "audios":
            controller = "AudiosDataController.do";
            break;
        case "photos":
            controller = "PhotosDataController.do";
            break;
        case "videos":
            controller = "VideosDataController.do";
            break;
    }
    var objMessage = dojo.query('#sidebar_info .synced')[0];
    objMessage.innerHTML = uploadingMessage;
    objMessage.style.color = 'red';
    objMessage.style.fontWeight = "bold";
    var extra = {
        postLoad: function(){
            loadSystemData();
			// ATTN: this query potentially has performance issues
			dojo.query(".list.items input[type='checkbox'][name='item']").forEach(function(item){ item.checked = false; });
        }
    }

    LoadData(controller, null, params, extra, true);
}

function deleteSingleFile(type, id){
    //var params = dojo.formToObject("itemsForm");
    var item = [id];
    var action = "delete";
    var params = {
        item: item,
        action: action
    }
    var controller;
    switch (type) {
        case "audios":
            controller = "AudiosDataController.do";
            break;
        case "photos":
            controller = "PhotosDataController.do";
            break;
        case "videos":
            controller = "VideosDataController.do";
            break;
        case "documents":
            controller = "DocumentsDataController.do";
            break;
    }
    galleryDeleteController = controller;
    galleryDeleteParams = params;
    //hideFlash();
    popUpDialog('alert', jsLocaleBundle["JS.POPUP.DELETE_ITEM.CONFIRM.MSG"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], 'executeDelete()')
    //LoadData(controller, "content", params);
}

function executeDelete(){
    showFlash();
    LoadData(galleryDeleteController, "content", galleryDeleteParams,galleryDeleteExtra,true);
	LoadData("ProfileDataController.do", "profile", null, null);    
}


var objOverlay;
function setOverlay(obj){
    objOverlay = obj;
}

function showPicOverlay(obj){
    if (obj) {
        setOverlay(obj);
    }
    //alert(objOverlay.className);
    if (objOverlay && objOverlay.childNodes) {
        //alert(objOverlay.childNodes.length);
        for (var i = 0; i < objOverlay.childNodes.length; i++) {
            //alert(objOverlay.childNodes[i].className);
            if (objOverlay.childNodes[i].className == 'photo_overlay') {
                objOverlay.childNodes[i].style.display = "block";
            }
        }
        if (objOverlay.className == 'photo_overlay') {
            objOverlay.style.display = "block";
        }
        //dojo.query(".photo_overlay",objOverlay)[0].style.display = "block";
    }
}

function hidePicOverlay(){
    if (objOverlay && objOverlay.childNodes) {
        for (var i = 0; i < objOverlay.childNodes.length; i++) {
            if (objOverlay.childNodes[i].className == 'photo_overlay') {
                objOverlay.childNodes[i].style.display = "none";
            }
        }
        //dojo.query(".photo_overlay",objOverlay)[0].style.display = "none";
    }
}

function updateImageDetails(id){
    if (isNaN(id)) {
        id = 0;
    }
    var params = {
        photoID: id,
        action: "load"
    };
    var extra = {
        postLoad: function(){
            var id = dojo.byId('imageID').value;
            dojo.byId('imageName' + id).innerHTML = dojo.byId('currentFileName').value;

            editPhotoApplyState(getCurEditPhotoNode());
        }
    }

    var controller = "PhotosEditInnerController.do";
    LoadData(controller, "details", params, extra);
}

function SortAudios(sortKey, ContactsDataUri, sortDirection){
    var sortDirection;
    if (sortDirection == "down") {
        sortDirection = "up";
    }
    else {
        sortDirection = "down";
    }
    var params = {
        sortKey: sortKey,
        sortDirection: sortDirection,
        action: "getSortedAudios"
    };
    LoadData(ContactsDataUri, "content", params,null,true);
}

function savePhoto(){
    var postFetch = {
        run: function(){
            if (commonJson && commonJson.fileUpdated == true && params && params.content.fileId) {
                dojo.byId('imageName' + params.content.fileId).innerHTML = dojo.byId('currentFileName').value;
            }

        }
    }
		/*if (FileExt(dojo.byId('imageName' + dojo.query("#editPhoto input[name='fileId']")[0].value).innerHTML)
		   != FileExt(dojo.byId('currentFileName').value)) {

		}*/
    saveFile("editPhoto", postFetch);
}

function saveVideo(){
    var postFetch = {
        run: function(){
            if (commonJson && commonJson.fileUpdated == true && params && params.content.fileId) {
                dojo.query("#videos_list .item_"+ params.content.fileId +" .filename")[0].innerHTML = cutStringToLength(dojo.query('#editVideo input.filename')[0].value, 15);
            }

        }
    }
	saveFile("editVideo", postFetch);
}

function saveAudio(){
    var postFetch = {
        run: function(){
            if (commonJson && commonJson.fileUpdated == true && params && params.content.fileId) {
				var node = dojo.query("#music .list.items .item_"+ params.content.fileId );
                node.query(".mediaTitle")[0].innerHTML = dojo.query('#edit_audio .mediaTitle')[0].innerHTML;
                node.query(".mediaArtist")[0].innerHTML = dojo.query('#edit_audio .mediaArtist')[0].innerHTML;
            }

        }
    }
    saveFile("editAudioForm", postFetch);
}

function saveFile(form, postFetch){
    var controller = "FileUpdateController.do";
    var params = dojo.formToObject(form);
    var extra = {
        postLoad: function(){
            var status = commonJson.fileUpdatedStatus;
            dojo.query('.top .status')[0].innerHTML = status;
            setTimeout("dojo.query('.top .status')[0].innerHTML = ''", 7000);
            if (postFetch && postFetch.run && typeof(postFetch.run) == 'function') {
                postFetch.run();
            }
        }
    }
    LoadData(controller, "none", params, extra);
}

function loadDocuments() {
    var extra = {
        postLoad: function(){
            currentPage = 'documents';
            hideFlash();
        }
    };
    LoadData('DocumentsDataController.do', 'content', null, extra, null, 'loadDocuments');
}

function SortDocuments(sortKey, DataUri, sortDirection) {
	var sortDirection
    if (sortDirection == "down") {
        sortDirection = "up";
    }
    else {
        sortDirection = "down";
    }
    var params = {
        sortKey: sortKey,
        sortDirection: sortDirection,
        action: "getSortedItems"
    };
    LoadData(DataUri, "content", params);
}

// being able to pass closures as button handlers to popup would eleminate the need for a global
var monitorFileExtentionUndo;
// usage onfocus='monitorFileExtention(this)'
function monitorFileExtention(inputNode) {
	var origExt = FileExt(inputNode.value).toLowerCase();
	var origValue = inputNode.value;
	//var origOnchange = inputNode.onchange; 
	inputNode.onkeyup = function(){
        monitorFileExtentionUndo = function() {
			inputNode.value = origValue;
		};
		if (origExt != FileExt(inputNode.value).toLowerCase()) {
			monitorFileExtentionUndo();
			popUpDialog('notice', jsLocaleBundle["JS.POPUP.FILE_EXTENTION.ALERT_MSG"], 
			    jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
		} else {
			origValue = inputNode.value;
		}
/*		inputNode.onchange = origOnchange;
		if (origOnchange && typeof(origOnchange) =="function" ) {
			origOnchange();
		}*/ 
	}
}
var SUNDAY = 1;
var MONDAY = 2;
var TUESDAY = 3;
var WEDNESDAY = 4;
var THURSDAY = 5;
var FRIDAY = 6;
var SATURDAY = 7;

function YMD(y, m, d){
    this.year = y;
    this.month = m;
    this.day = d;
    
    // receives YMD and _replaces_ any obviously invalid values with those taken from today's date
    this.sanitize = function(ymd){
        var D = new Date();
        if (isNaN(this.year) || this.year === '') {
            this.year = D.getFullYear();
        }
        if (isNaN(this.month) || this.month === '') {
            this.month = D.getMonth();
        }
        if (isNaN(this.day) || this.day === '') {
            this.day = D.getDate();
        }
    }
}

var googleCalendar;
function setGoggleCal(obj){
    googleCalendar = obj.value;
}

function loadCalendar(page, y, m, d, scroll){
    if (!scroll || isNaN(scroll)) {
        scroll = 336;
    }
    var ymd = new YMD(y, m, d);
    ymd.sanitize();
    extra = {
        postLoad: function(){
            switch (page) {
                case 'search':
                    dojo.query('#calendar .controls .delete')[0].style.display = 'block';
                    dojo.query('#calendar .controls .delete')[0].onclick = preDeleteCheckedEvents;
                    break;
                case 'allTasks':
                    dojo.query('#calendar .controls .delete')[0].style.display = 'block';
                    dojo.query('#calendar .controls .delete')[0].onclick = preDeleteCheckedTasks;
                    break;
                default:
                    dojo.query('#calendar .controls .delete')[0].style.display = 'none';
                    dojo.query('#calendar .controls .delete')[0].onclick = null;
            }
            var gCalFirst = dojo.query("#calendar .GOOGLE_CALENDAR.pluginIsFirstTime");
            if (gCalFirst && gCalFirst[0] && gCalFirst[0].innerHTML == "true") {
                var html = jsLocaleBundle['JS.SETTINGS.SECTIONS.GOOGLE_CALENDAR.CHOOSE_CALENDAR'];
                var firstLine = true;
                html += '<div class="googleCalendarSelect">';
                for (key in commonJson.googleCalendarsList) {
                    if (firstLine) {
                        googleCalendar = commonJson.googleCalendarsList[key].value;
                    }
                    html += '<div class="googleCalendarRow row"><input class="googleCalendarRadio" type="radio" ' + (firstLine ? 'CHECKED' : '') + ' onclick="setGoggleCal(this)"  name="gcal" value="' + commonJson.googleCalendarsList[key].value + '"/>' + commonJson.googleCalendarsList[key].key + '</div>';
                    firstLine = false;
                }
                html += '</div>';
                if (commonJson.googleCalendarsList.length > 1) {
                    popUpDialog('notice', html, jsLocaleBundle['JS.POPUP.TITLE.ATTENTION'], 'googleCalendarSync()');
                }
                else 
                    if (commonJson.googleCalendarsList.length == 1) {
                        googleCalendar = commonJson.googleCalendarsList[0].value;
                        googleCalendarSync();
                    }
            }
            else {
                loadSystemData();
            }
            currentPage = 'calendar';
            hideFlash();
            ScrollTo('#calendar .scroller', scroll);
        }
    };
    post = {
        year: ymd.year,
        month: ymd.month,
        day: ymd.day,
        subPage: 'calendarDailyContent'
    }
    target = "content";
    switch (page) {
        case "allTasks":
            uri = "CalendarTasksController.do";
            break;
        case "search":
        case "eventsSearch":
            uri = "CalendarSearchController.do";
            break;
        case "calendarWeeklyContent":
            post.subPage = 'calendarWeeklyContent';
        case "calendarDailyContent":
        default:
            uri = "CalendarDataController.do";
            break;
            
    }
    LoadData(uri, target, post, extra, null, 'loadCalendar');
}

function loadCalendarMonthBack(y, m, d, page){
    y = parseInt(y);
    m = parseInt(m);
    d = parseInt(d);
    if (m > 0) {
        m--;
    }
    else {
        m = 11;
        y--;
    }
    loadCalendar(page, y, m, d);
}

function loadCalendarMonthForth(y, m, d, page){
    y = parseInt(y);
    m = parseInt(m);
    d = parseInt(d);
    if (m < 11) {
        m++;
    }
    else {
        m = 0;
        y++;
    }
    loadCalendar(page, y, m, d);
}

function loadCalendarWeekBack(y, m, d, page){
    y = parseInt(y);
    m = parseInt(m);
    d = parseInt(d);
    var DT = new Date(y, m, d);
    DT.setDate(DT.getDate() - 7);
    d = DT.getDate();
    m = DT.getMonth();
    y = DT.getFullYear();
    loadCalendar(page, y, m, d);
}

function loadCalendarWeekForth(y, m, d, page){
    y = parseInt(y);
    m = parseInt(m);
    d = parseInt(d);
    var DT = new Date(y, m, d);
    DT.setDate(DT.getDate() + 7);
    d = DT.getDate();
    m = DT.getMonth();
    y = DT.getFullYear();
    loadCalendar(page, y, m, d);
}

function taskAction(action, reload){
    var params = dojo.formToObject("editTaskForm");
    params.action = action;
    if (params.VCalID == undefined || params.VCalID == "") {
        params.VCalID = "0";
    }
    if (reload) {
        closePopUp();
        params.subPage = dojo.byId('subPage').value;
        LoadData("EventEditController.do", "content", params, null, null, 'loadCalendar');
    }
    else {
        LoadData("EventEditController.do", "content", params);
    }
}

function saveEvent(form){
    var scroll;
    var scrollerNode = dojo.query("#calendar .scroller")[0];
    if (scrollerNode) {
        scroll = scrollerNode.scrollTop;
    }
if ((form != 'editTaskForm') && (document.getElementById('event_allDay').checked)) {
        document.getElementById('event_end_date').value = getNextDay(document.getElementById('event_end_date').value);
 }
    var params = dojo.formToObject(form || "editEventForm");
    params.action = "save";
    if (form != 'editTaskForm') {
        if (!checkEditEventInterval('big')) {
            return false;
        }
    }
    
    if (params.VCalID == undefined || params.VCalID == "") {
        params.VCalID = "0";
    }
    params.subPage = dojo.byId('subPage').value;
    extra = {
        postLoad: function(){
            if (currentPage == 'home') {
                loadHome();
                loadSystemData();
            }
            else {
                loadCalendar(params.subPage, dojo.byId('y').value, dojo.byId('m').value, dojo.byId('d').value, scroll);
            }
        }
    };
    if (form != 'editTaskForm') {
        if (!isStringDatesOk(params.start_date, params.start_time, params.end_date, params.end_time)) {
            params.end_date = params.start_date;
            params.end_time = params.start_time;
        }
    }
    LoadData("EventEditController.do", null, params, extra, true);
}

var eventEditFormParams;

function startDeleteEvent(form, alert){
    eventEditFormParams = dojo.formToObject(form || "editEventForm");
    popUpDialog('alert', alert, 'Confirm', "deleteEvent()");
}

function startDeleteRecurence(form, alert){
    eventEditFormParams = dojo.formToObject(form || "editEventForm");
    popUpDialog('alert', alert, 'Confirm', "deleteEvent(true)");
}

function deleteEvent(rec){
    var params = eventEditFormParams;
    if (rec) {
        params.action = "deleteRecurrence";
    }
    else {
        params.action = "delete";
    }
    if (params.VCalID == undefined || params.VCalID == "") {
        return false;
    }
    closePopUp();
    params.subPage = dojo.byId('subPage').value;
    //LoadData("EventEditController.do", "none", params, null, null, 'loadCalendar');
    extra = {
        postLoad: function(){
            if (currentPage == 'home') {
                loadHome();
                loadSystemData();
            }
            else {
                loadCalendar(params.subPage, dojo.byId('y').value, dojo.byId('m').value, dojo.byId('d').value, scroll);
            }
            
        }
    };
    LoadData("EventEditController.do", "none", params, extra, true);
    
}

function checkTimeField(obj, backupID){
    value = obj.value;
    objBackup = dojo.byId(backupID);
    var pattern = /(\d?)(\d):(\d?)(\d)/;
    if (!pattern.test(value)) {
        obj.value = objBackup.value;
        return false;
    }
    var matcher = pattern.exec(value);
    
    var hours = matcher[1] + matcher[2];
    var minutes = matcher[3] + matcher[4];
    
    if (hours.length == 1) {
        //Add a leading 0
        hours = "0" + hours;
    }
    if (minutes.length == 1) {
        minutes = "0" + minutes;
    }
    value = hours + ":" + minutes;
    if (minutes >= 0 && minutes < 60 && hours >= 0 && hours < 24) {
        obj.value = value;
        objBackup.value = value;
        return true;
    }
    obj.value = objBackup.value;
    popUpDialog('tooltip', jsLocaleBundle['JS.CALENDAR.TIME_FORMAT.MSG']);
    return false;
}

function rotateTimeField(e, backupID){
    var code = parseInt(e.keyCode);
    if (code < 37 || code > 40) {
        return true;
    }
    if (!checkTimeField(e.target, backupID)) {
        return false;
    }
    var selection;
    if (e.target.selectionEnd <= e.target.value.indexOf(':')) {
        selection = 0;
    }
    else {
        selection = 1;
    }
    var diff;
    if (code == 38) {
        diff = 1;
    }
    if (code == 40) {
        diff = -1;
    }
    if (code == 39) {
        selection = 1;
    }
    if (code == 37) {
        selection = 0;
    }
    arrNums = e.target.value.split(':');
    arrNums[0] = parseInt(trimNull(arrNums[0]));
    arrNums[1] = parseInt(trimNull(arrNums[1]));
    if (diff && diff != 0) {
        if (selection == 0) {
            arrNums[0] += diff;
        }
        else {
            arrNums[1] += diff;
        }
    }
    if (arrNums[1] > 59) {
        arrNums[1] = 0;
        arrNums[0]++;
    }
    if (arrNums[1] < 0) {
        arrNums[1] = 59;
        arrNums[0]--;
    }
    if (arrNums[0] > 23) {
        arrNums[0] = arrNums[0] - 24;
    }
    if (arrNums[0] < 0) {
        arrNums[0] = arrNums[0] + 24;
    }
    
    if (arrNums[0] < 10) {
        arrNums[0] = '0' + arrNums[0];
    }
    if (arrNums[1] < 10) {
        arrNums[1] = '0' + arrNums[1];
    }
    e.target.value = arrNums[0] + ':' + arrNums[1];
    if (selection == 0) {
        e.target.selectionStart = 0;
        e.target.selectionEnd = e.target.value.indexOf(':')
    }
    else {
        e.target.selectionStart = e.target.value.indexOf(':') + 1;
        e.target.selectionEnd = e.target.value.length;
    }
}

function calendarSearch(){
    uri = "CalendarSearchController.do";
    target = "content";
    var post = dojo.formToObject(dojo.query('#calendar form.search')[0]);
    post.action = 'search';
    LoadData(uri, target, post, null, true);
}

function calendarSearchClear(){
    uri = "CalendarSearchController.do";
    target = "content";
    var post = {
        action: 'search'
    };
    LoadData(uri, target, post, null, true);
}

function taskPopUp(title, id, page){
    var uri = "TaskEditController.do";
    var params = {
        action: "loadTask",
        VCalID: id,
        fromPage: page,
        pageNum: 0
    };
    LoadHtmlToPopup(uri, params, title, null);
}

function eventPopUp(title, id, page, pageNumber){
    var uri = "EventEditController.do";
    
    var params = {
        action: "load",
        VCalID: id,
        fromPage: page,
        pageNum: parseInt(pageNumber),
        year: 0,
        month: 0,
        day: 0,
        page: pageNumber
    };
    
    if (params.VCalID == undefined || params.VCalID == "") {
        params.VCalID = "0";
    }
    
    if (dojo.byId('y') && dojo.byId('m') && dojo.byId('d')) {
        params.year = parseInt(dojo.byId('y').value);
        params.month = parseInt(dojo.byId('m').value);
        params.day = parseInt(dojo.byId('d').value);
    }
    var ymd = new YMD(params.year, params.month, params.day);
    ymd.sanitize();
    params.year = ymd.year;
    params.month = ymd.month;
    params.day = ymd.day;
    
    extra = {
        postLoad: function(){
            var categoryType = document.getElementById('eventType');
            
            if (categoryType.value == 'ANNIVERSARY') {
                dojo.query("#editEvent .recurrence .tabs .label input[type='radio']:not([value='yearly'])").forEach(function(item){
                    item.disabled = true;
                });
            }
            changeTime(categoryType.value);
            if (document.getElementById('event_allDay').checked && document.getElementById('event_end_date').value != document.getElementById('event_start_date').value) {
                document.getElementById('event_end_date').value = getPrevDay(document.getElementById('event_end_date').value);
                setAllDay();
            }
        }
    };
    LoadHtmlToPopup(uri, params, title, null, extra);
    setRecType();
}

var strCurrentRepeatTypeId = "none";
function setRecType(){
    strCurrentRepeatTypeId = "none"
    var strRepeatTypeId;
    if (dojo.byId('recType')) {
        var recType = dojo.byId('recType').value;
        switch (recType) {
            case 'D':
                strRepeatTypeId = "daily";
                break;
            case 'W':
                strRepeatTypeId = "weekly";
                break;
            case 'M':
                strRepeatTypeId = "monthly";
                break;
            case 'Y':
                strRepeatTypeId = "yearly";
                break;
        }
        if (strRepeatTypeId) {
            chooseRepeatType(dojo.query("#editEvent .recurrence .tabs input[value='" + strRepeatTypeId + "']")[0]);
        }
    }
}

function chooseRepeatType(objInput){
    var strRepeatTypeToShowId = objInput.value;
    dojo.byId('recurrenceEveryUnit').innerHTML = jsLocaleBundle['JS.RECURRENCE_EVERY.UNIT.' + strRepeatTypeToShowId.toUpperCase()];
    var objDivToShow = dojo.byId('tab_recurrence_' + strRepeatTypeToShowId);
    var objDivToHide = dojo.byId('tab_recurrence_' + strCurrentRepeatTypeId);
    if (objDivToShow && objDivToHide && (objDivToShow != objDivToHide)) {
        objDivToHide.style.display = "none";
        objDivToShow.style.display = "block";
        var newUnit = dojo.query(".unit", objDivToShow);
        var unit = dojo.query("#editEvent .recurrence .content .every .unit")[0];
        if (newUnit.length > 0) {
            //unit.innerHTML = newUnit.innerHTML;
        }
        dojo.query("#editEvent .recurrence .content .every,#editEvent .recurrence .content .range").style("display", (newUnit.length > 0) ? "block" : "none");
        strCurrentRepeatTypeId = strRepeatTypeToShowId;
    }
}

//var allDayTimeout;
function closeAllDays(){
    //    clearTimeout(allDayTimeout);
    //event = getEvent(e);
    //if (event.relatedTarget.className.indexOf('allDay') == -1) {
    dojo.query('#tab_daily .allDay .list').removeClass('open');
    //}
}

function openAllDaysFunc(){
    dojo.query('#tab_daily .allDay .list').addClass('open');
}

function openAllDays(){
    //    allDayTimeout = setTimeout(openAllDaysFunc, 300);
    dojo.query('#tab_daily .allDay .list').addClass('open');
}

/*** search paging ***/
function calendarNextPage(){
    var params = {
        action: "next",
        pageNum: 0,
        searchKey: dojo.byId('searchKey').value
    }
    var controller = "CalendarSearchController.do";
    LoadData(controller, "content", params, null, true);
}

function calendarPrevPage(){
    var params = {
        action: "prev",
        pageNum: 0,
        searchKey: dojo.byId('searchKey').value
    }
    var controller = "CalendarSearchController.do";
    LoadData(controller, "content", params, null, true);
}

function calendarNumPage(num){
    var params = {
        action: "pageByNum",
        pageNum: num,
        searchKey: dojo.byId('searchKey').value
    }
    var controller = "CalendarSearchController.do";
    LoadData(controller, "content", params, null, true);
}

function completeTask(vCalId){
    // var params = dojo.formToObject(form || "editEventForm");
    var params = {
        action: 'completeTask',
        VCalID: vCalId
    }
    var subPage = dojo.byId('subPage').value;
    extra = {
        postLoad: function(){
            if (currentPage == 'home') {
                loadHome();
            }
            else {
                loadCalendar(subPage, dojo.byId('y').value, dojo.byId('m').value, dojo.byId('d').value);
            }
        }
    };
    LoadData("EventEditController.do", "none", params, extra, true);
}

function uncompleteTask(vCalId){
    // var params = dojo.formToObject(form || "editEventForm");
    var params = {
        action: 'uncompleteTask',
        VCalID: vCalId
    }
    var subPage = dojo.byId('subPage').value;
    extra = {
        postLoad: function(){
            if (currentPage == 'home') {
                loadHome();
            }
            else {
                loadCalendar(subPage, dojo.byId('y').value, dojo.byId('m').value, dojo.byId('d').value);
            }
        }
    };
    LoadData("EventEditController.do", "none", params, extra, true);
}

function deleteTask(vCalId){
    // var params = dojo.formToObject(form || "editEventForm");
    var params = {
        action: 'delete',
        VCalID: vCalId,
        isTask: 1
    }
    var subPage = dojo.byId('subPage').value;
    extra = {
        postLoad: function(){
            if (currentPage == 'home') {
                loadHome();
            }
            else {
                loadCalendar(subPage, dojo.byId('y').value, dojo.byId('m').value, dojo.byId('d').value);
            }
        }
    };
    LoadData("EventEditController.do", "none", params, extra, true);
}

function checkDatesInterval(idSmallD, idSmallT, idBigD, idBigT, change){
    dojo.addClass(dojo.byId(idSmallD), '');
    dojo.addClass(dojo.byId(idSmallT), '');
    dojo.addClass(dojo.byId(idBigD), '');
    dojo.addClass(dojo.byId(idBigT), '');
    smallD = getValue(idSmallD);
    smallT = getValue(idSmallT);
    bigD = getValue(idBigD);
    bigT = getValue(idBigT);
    if (!isStringDatesOk(smallD, smallT, bigD, bigT)) {
        if (change == 'small') {
            setValue(idSmallD, bigD);
            setValue(idSmallT, bigT);
            dojo.addClass(dojo.byId(idSmallD), 'inputAttention');
            dojo.addClass(dojo.byId(idSmallT), 'inputAttention');
        }
        else {
            setValue(idBigD, smallD);
            setValue(idBigT, smallT);
            dojo.addClass(dojo.byId(idBigD), 'inputAttention');
            dojo.addClass(dojo.byId(idBigT), 'inputAttention');
        }
        return false;
    }
    else {
        dojo.removeClass(dojo.byId(idSmallD), 'inputAttention');
        dojo.removeClass(dojo.byId(idSmallT), 'inputAttention');
        dojo.removeClass(dojo.byId(idBigD), 'inputAttention');
        dojo.removeClass(dojo.byId(idBigT), 'inputAttention');
        return true;
    }
}

function isStringDatesOk(smallD, smallT, bigD, bigT){
    var smallArrD = smallD.split('/');
    var smallArrT = smallT.split(':');
    var bigArrD = bigD.split('/');
    var bigArrT = bigT.split(':');
    var smallDate = new Date(smallArrD[2], smallArrD[0], smallArrD[1], smallArrT[0], smallArrT[1]);
    var bigDate = new Date(bigArrD[2], bigArrD[0], bigArrD[1], bigArrT[0], bigArrT[1]);
    if (smallDate.getTime() > bigDate.getTime()) {
        showEditEventError(jsLocaleBundle["JS.EDIT_EVENT.DATES_NOT_MATCH.MSG"]);
        return false;
    }
    else {
        return true;
    }
}

function checkEditEventInterval(change){
    var categoryType = document.getElementById('eventType');    
    if (categoryType.value == 'ANNIVERSARY' || categoryType.value == 'CALL') {
        //document.getElementById('event_end_date').value = getNextDay(document.getElementById('event_start_date').value) ;
        return true;
    }
    return checkDatesInterval('event_start_date', 'event_start_time', 'event_end_date', 'event_end_time', change);
}


function changeTime(eventType){
    var startDate = document.getElementById('event_start_date');
    var startTime = document.getElementById('event_start_time');
    var startTimeBackup = document.getElementById('event_start_time_backup');
    var endDate = document.getElementById('event_end_date');
    var endTime = document.getElementById('event_end_time');
    var endTimeBackup = document.getElementById('event_end_time_backup');
    // nullify state
    dojo.query("#editEvent .recurrence .tabs .label input[type='radio']").forEach(function(item){
        item.disabled = false;
    });
    startTime.disabled = false;
    endTime.disabled = false;
    endDate.onclick = function(){
        DP.datePicker('event_end_date', 2000, 2020, 53, 400, 'DPsource', null, true)
    };
    dojo.query("#editEvent .endDate input").forEach(function(item){
        unsetReadonly(item);
    });
    dojo.query("#editEvent .allDayCell input")[0].disabled = false;
    unsetReadonly(endTime);
    unsetReadonly(endDate);
    
    
    
    
    if (eventType == 'ANNIVERSARY') {
        var yearlyRadioSelector = dojo.query("#editEvent .recurrence .tabs .label input[type='radio'][value='yearly']")[0];
        yearlyRadioSelector.checked = "checked";
        chooseRepeatType(yearlyRadioSelector);
        dojo.query("#editEvent .recurrence .tabs .label input[type='radio']:not([value='yearly'])").forEach(function(item){
            item.disabled = true;
        });
    }
    if (eventType == 'MEMO' || eventType == 'ANNIVERSARY') {
        document.getElementById('event_allDay').checked = true;
        startTime.value = '00:00';
        startTimeBackup.value = '00:00';
        startTime.disabled = true;
        endTime.value = '00:00';
        endTimeBackup.value = '00:00';
        endTime.disabled = true;
        if (eventType == 'ANNIVERSARY') {
            endDate.onclick = null;
            dojo.query("#editEvent .endDate input").forEach(function(item){
                setReadonly(item);
            });
            endDate.value = startDate.value;
        }
        dojo.query("#editEvent .allDayCell input")[0].disabled = true;
    }
    switchAllDay(document.getElementById('event_allDay'));
    if (eventType == 'CALL') {
        endTime.value = startTime.value;
        endDate.value = startDate.value;
        setReadonly(endTime);
        setReadonly(endDate);
        endDate.onclick = null;
    }
}

function setReadonly(obj){
    obj.readonly = true;
    obj.style.background = '#EFEFD1';
}

function unsetReadonly(obj){
    obj.readonly = false;
    obj.style.background = '';
}

function getNextDay(day){
    var arrDate = day.split("/");
    var date = new Date(parseInt(arrDate[2]), parseInt(cleanFirstNull(arrDate[0])) - 1, parseInt(cleanFirstNull(arrDate[1])));
    var newDate = new Date(date.getTime() + 24 * 60 * 60 * 1000);
    return formatNumberForDate((newDate.getMonth() + 1)) + "/" + formatNumberForDate(newDate.getDate()) + "/" + newDate.getFullYear();
}

function getPrevDay(day){
    var arrDate = day.split("/");
    var date = new Date(parseInt(arrDate[2]), parseInt(cleanFirstNull(arrDate[0])) - 1, parseInt(cleanFirstNull(arrDate[1])));
    var newDate = new Date(date.getTime() - 24 * 60 * 60 * 1000);
    return formatNumberForDate((newDate.getMonth() + 1)) + "/" + formatNumberForDate(newDate.getDate()) + "/" + newDate.getFullYear();
}

function cleanFirstNull(str){
	if(str.charAt(0) == '0'){
		str = str.slice(1);
	}
	return str;
}

function formatNumberForDate(num){
    if (num < 10) {
        num = '0' + num;
    }
    return num;
}

function setAllDay(){
    var startDate = document.getElementById('event_start_date');
    var startTime = document.getElementById('event_start_time');
    var startTimeBackup = document.getElementById('event_start_time_backup');
    var endDate = document.getElementById('event_end_date');
    var endTime = document.getElementById('event_end_time');
    var endTimeBackup = document.getElementById('event_end_time_backup');
    startTime.value = '00:00';
    startTimeBackup.value = '00:00';
    startTime.disabled = true;
    setReadonly(startTime);
    setReadonly(endTime);
    endTime.value = '00:00';
    endTimeBackup.value = '00:00';
    endTime.disabled = true;
}

function unsetAllDay(){
    var startTime = document.getElementById('event_start_time');
    var endTime = document.getElementById('event_end_time');
    startTime.disabled = false;
    endTime.disabled = false;
    unsetReadonly(startTime);
    unsetReadonly(endTime);
}

function switchAllDay(obj){
    if (obj.checked) {
        setAllDay();
    }
    else {
        unsetAllDay();
    }
}

function showEditEventError(message){
    dojo.query(" #form_content .status")[0].innerHTML = message;
    dojo.query(" #form_content .status").style({
        visibility: "visible",
        color: "red"
    });
}

function checkAlarmEnabled(obj){
    if (obj.checked) {
        dojo.byId('task_reminder_date').disabled = false;
        dojo.byId('task_reminder_time').disabled = false;
    }
    else {
        dojo.byId('task_reminder_date').disabled = true;
        dojo.byId('task_reminder_time').disabled = true;
    }
}

function googleCalendarSync(){
    var post = {
        action: "googleCalendarSync",
        calendar: googleCalendar
    };
    var objMessage = dojo.query('#sidebar_info .synced')[0];
    if (objMessage.style.color == 'red') {
        return;
    }
    objMessage.innerHTML = jsLocaleBundle["JS.CALENDAR.GOOGLE_SYNC_IN_PROGRESS"];
    objMessage.style.color = 'red';
    objMessage.style.fontWeight = "bold";
    dojo.query("#GOOGLE_CALENDARform .button").style('display', 'none');
    var extra = {
        postLoad: function(){
            dojo.query("#GOOGLE_CALENDARform .button").style('display', 'block');
            if (currentPage == 'calendar') {
                loadCalendar('', '', '', '');
            }
            else {
                loadSystemData();
            }
        }
    }
    LoadData('CalendarDataController.do', null, post, extra, true);
}

function preDeleteCheckedEvents(){
    var params = dojo.formToObject("eventSearchItemsForm");
    if (!params.item || params.item < 1) {
        popUpDialog('notice', jsLocaleBundle["JS.CALENDAR.DELETE_EVENTS.PLEASE_SELECT"], 'Confirm', null);
    }
    else {
        popUpDialog('alert', jsLocaleBundle["JS.CALENDAR.DELETE_EVENTS.CONFIRM"], 'Confirm', 'deleteCheckedEvents()');
    }
}


function deleteCheckedEvents(){
    var params = dojo.formToObject("eventSearchItemsForm");
    uri = "CalendarSearchController.do";
    target = "content";
    var post = dojo.formToObject(dojo.query('#calendar form.search')[0]);
    post.action = 'searchDelete';
    post.item = params.item;
    post.pageNum = params.pageNum;
    LoadData(uri, target, post, null, true);
}

function preDeleteCheckedTasks(){
    var params = dojo.formToObject("allTasksItemsForm");
    if (!params.item || params.item < 1) {
        popUpDialog('notice', jsLocaleBundle["JS.CALENDAR.DELETE_EVENTS.PLEASE_SELECT"], 'Confirm', null);
    }
    else {
        popUpDialog('alert', jsLocaleBundle["JS.CALENDAR.DELETE_EVENTS.CONFIRM"], 'Confirm', 'deleteCheckedTasks()');
    }
}


function deleteCheckedTasks(){
    var params = dojo.formToObject("allTasksItemsForm");
    uri = "CalendarTasksController.do";
    target = "content";
    params.action = 'allTasksDelete';
    extra = {
        postLoad: function(){
            dojo.query('#calendar .controls .delete')[0].onclick = preDeleteCheckedTasks;
        }
    }
    LoadData(uri, target, params, null, true);
}

function loadProfileArea(){
	LoadData("ProfileDataController.do", "profile", null, null);
}

function performAction(action){
    var params = dojo.formToObject("actionsForm");
    params.actionToPerform = action;
    var extra = {
        postLoad: function(){
            if (commonJson.sidebarPostLoad) {
                try {
                    eval(commonJson.sidebarPostLoad);
                } 
                catch (e) {
                
                }
            }
        }
    };
    LoadData("SidebarActionsController.do", null, params,extra);
}

function confirmWipeout(avare){
    popUpDialog('excl', jsLocaleBundle["JS.SIDEBAR.ACTIONS.WIPEOUT.MSG"], jsLocaleBundle["JS.POPUP.TITLE.WARNING"], "performAction('wipeout')");
}

function confirmDeleteUser(avare){
    popUpDialog('excl', jsLocaleBundle["JS.SIDEBAR.ACTIONS.DELETE_USER.MSG"], jsLocaleBundle["JS.POPUP.TITLE.WARNING"], "performAction('delete_user')");
}

function backupAction(){
    popUpDialog('alert', jsLocaleBundle["JS.SIDEBAR.ACTIONS.BACKUP.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], "performAction('backup')");
}

function restoreAction(){
    popUpDialog('alert', jsLocaleBundle["JS.SIDEBAR.ACTIONS.RESTORE.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], "performAction('restore')");
}

function readSysMessage(){
    var params = {
        action: 'readSysMessage'
    };
    var extra = {
        postLoad: function(){
			//loadSystemData() or is the next line needed at all?
            LoadData("DataDataController.do", "data", null, null);
        }
    };
	closePopUp();
    LoadData('DataDataController.do', 'data', params);
}

function popSystemMessage(){
	if(dojo.byId('sysMessageHiddenLink')){
		readSysMessage();
	}else if (dojo.byId('sysPriority') && dojo.byId('sysPriority').value == 1) {
        dojo.byId('sysMessageButton').onclick();
    }
}

function loadProfile(){
    var params = {
        action: 'loadSelfVCard'
    };
    LoadHtmlToPopup("ContactsEditController.do", params, jsLocaleBundle["JS.ADD_CONTACTS.SELF.TITLE"], null);
    takeValuesToMain();
    setTimeout(loadContactPics, 1000);
}

function logout(){
	window.location = 'LogoutController.do';
}
dojo.require("dojo.cookie");
function loadSettings(tab){
    var extra = {
        postLoad: function(){
            currentPage = 'settings';
            hideFlash();
            if (tab) {
                settingsSwitchTab(tab);
                if (tab == "SERVICES") {
                    if (dojo.query("#GOOGLE_CONTACTSform .pluginIsFirstTime")[0].innerHTML == "true") {
                        popUpDialog('alert', jsLocaleBundle['JS.SETTINGS.SECTIONS.GOOGLE_CONTACTS.DO_YOU_WANT_TO_SYNC_ONLY_WITH_PHONES'], jsLocaleBundle['JS.POPUP.TITLE.ATTENTION'], 'googleSyncContacts()', true, 'googleSyncContacts(false)');
                    }
                    if (dojo.query("#GOOGLE_CALENDARform .pluginIsFirstTime")[0].innerHTML == "true") {
                        var html = jsLocaleBundle['JS.SETTINGS.SECTIONS.GOOGLE_CALENDAR.CHOOSE_CALENDAR'];
                        var firstLine = true;
                        html += '<div class="googleCalendarSelect">';
                        for (key in commonJson.googleCalendarsList) {
                            if (firstLine) {
                                googleCalendar = commonJson.googleCalendarsList[key].value;
                            }
                            html += '<div class="googleCalendarRow row"><input class="googleCalendarRadio" type="radio" ' + (firstLine ? 'CHECKED' : '') + ' onclick="setGoggleCal(this)"  name="gcal" value="' + commonJson.googleCalendarsList[key].value + '"/>' + commonJson.googleCalendarsList[key].key + '</div>';
                            firstLine = false;
                        }
                        html += '</div>';
                        if (commonJson.googleCalendarsList.length > 1) {
                            popUpDialog('notice', html, jsLocaleBundle['JS.POPUP.TITLE.ATTENTION'], 'googleCalendarSync()');
                        }
                        else if(commonJson.googleCalendarsList.length == 1) {
                            googleCalendar = commonJson.googleCalendarsList[0].value;
                            googleCalendarSync();
                        }                       
                    }
                }
            }
            else {
                var h = dojo.query('.settings_tab_content')[0].scrollHeight;
                dojo.query('.settings_tab_content')[0].style.height = h + 'px';
            }
        }
    };
    LoadData('SettingsDataController.do', 'content', null, extra, null, 'loadSettings');
}

function showLanguages(){
    dojo.query('.flash').style('visibility', 'hidden');
    dojo.byId('languages').style.display = '';
}

function closeLang(){
    dojo.query('.flash').style('visibility', 'visible');
    dojo.byId('languages').style.display = 'none';
}


function changeLanguage(langId, outer){
    if (outer) {
        var uri = 'SetLanguageController.do';
    }
    else {
        var uri = 'UserSettingsController.do';
    }
    var post = {
        action: 'changeLanguage',
        langID: langId
    };
    var extra = {
        postLoad: function(){
            window.location.reload(true);
        }
    };
    LoadData(uri, null, post, extra);
}

function settingsApply(section, postFetch){
    if (isEmptyInputsInForm(section + "form")) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.PLEASE_FILL_ALL_FIELDS.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
        return;
    }
    var params = dojo.formToObject(section + "form");
    params.id = "settings_section_" + section;
    params.title = section;
    params.action = 'update' + section;
    var extra = {
        postLoad: function(){
            if (postFetch && postFetch.run && typeof(postFetch.run) == 'function') {
                postFetch.run();
            }
            if (commonJson.settingsPostLoad) {
                try {
                    eval(commonJson.settingsPostLoad);
                } 
                catch (e) {
                
                }
            }
            if (commonJson.settingsUpdated && dojo.byId(section + 'status')) {
                dojo.byId(section + 'status').innerHTML = commonJson.settingsUpdated;
                setTimeout("if(dojo.byId('" + section + 'status' + "')){dojo.byId('" + section + 'status' + "').innerHTML = ''}", 7000);
            }
        }
    }
    LoadData("SettingsDataController.do", null, params, extra);
}


function settingsApplyEmail(section){
    var params = dojo.formToObject(section + "form");
    if (isEmptyInputsInForm(section + "form")) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.EMAIL.PLEASE_INPUT_NEW_EMAIL.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
        return;
    }
    if (dojo.trim(params.new_email) ==
    dojo.trim(dojo.query("#" + section + "form input[name='current_email']")[0].value)) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.EMAIL.SAME_AS_CURRENT.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
    }
    else {
        //settingsApply(section, {run: function () { dojo.query("#"+ section +"form input[name='new_email']")[0].value = ''; } } );
        
        popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.EMAIL.ALERT"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], "settingsApply('" + section + "', {run: function () { dojo.query('#" + section + "form input[name=\\'new_email\\']')[0].value = ''; } } )");
    }
}

function settingsApplyPassword(section){
    var params = dojo.formToObject(section + "form");
    if (isEmptyInputsInForm(section + "form")) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.EMAIL.PLEASE_INPUT_NEW_PASSWORD.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
        return;
    }
    if (params.new_password2 != params.new_password) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.PASSWORD.UNMATCHING.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
    }
    else {
        popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.PASSWORD.ALERT"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], "settingsApply('" + section + "')");
    }
}

function settingsApplyMsisdn(section){
    var params = dojo.formToObject(section + "form");
    if (isEmptyInputsInForm(section + "form")) {
        popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.SECTIONS.EMAIL.PLEASE_INPUT_NEW_MSISDN.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], null);
        return;
    }
    popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.MSISDN.ALERT"], jsLocaleBundle["JS.POPUP.TITLE.CONFIRM"], 'msisdnApply()')
}


function msisdnApply(){
    var postFetch = {
        run: function(){
            if (commonJson.systemState && commonJson.systemState == 'success') {
                window.location = 'LogoutController.do';
            }
        }
    }
    settingsApply('MSISDN', postFetch)
}

function settingsOnChangeCountryCode(node){
    if (node) {
        var timezone = commonJson.CountryCode2Timezone[node.options[node.selectedIndex].value];
        var list = dojo.filter(dojo.byId('changeTZ').options, function(item){
            return item.value.indexOf(timezone) >= 0;
        });
        if (list.length > 0) {
            list[0].selected = true;
        }
    }
    
    var objPrefix = dojo.query("#MSISDNform select[name='country']")[0];
    var objFull = dojo.query("#MSISDNform input#newMsisdn")[0];
    var prefix = objPrefix.options[objPrefix.selectedIndex].value;
    var number = dojo.query("#MSISDNform input#partialMsisdn")[0].value;
    if (prefix.length > 0) {
        dojo.query("#MSISDNform .phonePrefix")[0].innerHTML = '+' + prefix;
        if (number.length > 0 && !isNaN(number)) {
            objFull.value = prefix + number;
        }
        else {
            objFull.value = '';
        }
    }
    else {
        objFull.value = '';
    }
}

function enablePlugin(pluginName){
    var postFetch = {
        run: function(){
            if (dojo.query("#" + pluginName.toUpperCase() + "form .pluginIsSessionValid")[0].innerHTML != "true") {
                pluginAuthPopup(pluginName);
            }
        }
    }
    if (dojo.query("#" + pluginName.toUpperCase() + "form .pluginIsEnabled")[0].innerHTML == "true") {
        postFetch.run();
        return;
    }
    settingsApply(pluginName.toUpperCase(), postFetch)
}

function settingsSwitchTab(name){
    dojo.query(".settings_tab_content .tab").removeClass("active");
    dojo.addClass(dojo.byId("settings_tab_" + name), "active");
    dojo.query("#settings_tabs .cover").removeClass("active");
    dojo.addClass(dojo.byId("settings_" + name), "active");
    var appState = new ApplicationState('SettingsDataController.do', null, null, "loadSettings-" + name);
    dojo.back.addToHistory(appState);
    
    if (name == "SERVICES") {
        currentPage = "inetsvcs";
    }
    var h = dojo.query('.settings_tab_content')[0].scrollHeight;
    dojo.query('.settings_tab_content')[0].style.height = h + 'px';
}

function pluginAuthPopup(plugin){
    var params = {
        pluginName: plugin.toUpperCase()
    }
    var extra = {
        postLoad: function(){
            var url = commonJson.pluginUrl;
            if (dojo.byId(params.pluginName + 'status')) {
                dojo.byId(params.pluginName + 'status').innerHTML = jsLocaleBundle["JS.SETTINGS.SECTIONS." + params.pluginName + ".ENABLE.STATUS"];
                setTimeout("dojo.byId('" + params.pluginName + 'status' + "').innerHTML = ''", 7000);
            }
            var newwindow = window.open(url, 'Authenticate', 'height=436,width=800,scrollbars');
            if (!newwindow) {
                popUpDialog('notice', jsLocaleBundle['JS.POPUP.PLEASE_ENABLE_POPUPS'], jsLocaleBundle['JS.POPUP.TITLE.ATTENTION'])
            }
            if (newwindow && window.focus) {
                newwindow.focus()
            }
        }
    }
    LoadData('PluginUrlController.do', 'null', params, extra, true);
}

function unblockDevice(id){
    var params = {
        action: 'unblockDevice',
        deviceId: id
    }
    var extra = {
        postLoad: function(){
            settingsSwitchTab('MAINTENANCE');
            LoadData("ProfileDataController.do", "profile", null, null);
        }
    }
    LoadData("SettingsDataController.do", 'content', params, extra, true);
}

function clearPassword(){
    setValue('new_password', '');
    setValue('new_password2', '');
}

function askForGoogleContacts(){
    //if (!dojo.byId('googleContactsSyncOnlyWithPhones').checked) {
    //    popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.GOOGLE_CONTACTS.DO_YOU_WANT_TO_SYNC_ONLY_WITH_PHONES"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], 'enableGoogleContacts(true)', null, 'enableGoogleContacts(false)');
    //}
    //else {
    enableGoogleContacts();
    //}
}

function enableGoogleContacts(isOnlyWhisPhone){
    //dojo.byId('googleContactsSyncOnlyWithPhones').checked = isOnlyWhisPhone;
    enablePlugin('GOOGLE_CONTACTS');
}

function downloadOutlookAgent(){
    popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.OUTLOOK.WARNING"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], 'downloadOutlookAgentExe()');
}

function downloadOutlookAgentExe(){
    window.location = 'outlook.jsp';
}

function handlePluginResponse(pluginName){
    alert(pluginName);
}

function loadPayment(type){
    var controller;
    var extra;
    switch (type) {
		case 'globe':
            controller = 'GlobePaymentController.do';
            break;
		default:
		    type = 'plimus';
            controller = 'PaymentController.do';
            break;
    }
    
    LoadData(controller, 'content', null, null, null, 'loadPayment-' + type);
}

function isEmptyInputsInForm(formId){
    var queryString = "#" + formId + " input";
    var emptyValuesList = dojo.query(queryString).filter(function(item){
        return ((item.value == "") && (getInputType(item) == "text" || getInputType(item) == "password"));
    });
    if (emptyValuesList.length > 0) {
        return true;
    }
    else {
        return false;
    }
}

function confirmDeleteUserRecurring(){
    popUpDialog('alert', jsLocaleBundle["JS.SETTINGS.SECTIONS.DELETE_USER_RECURRING.WARNING"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"], 'goPlimus()');
}

function goPlimus(){
    window.location = "https://secure.plimus.com/jsp/account_login.jsp";
}

function duplicateAction(){
	popUpDialog('notice', jsLocaleBundle["JS.SETTINGS.DUPLICATE.STARTED"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"]);
	settingsApply("DUPLICATE");
}
/**
 *
 * @param {String} strId
 * @param {int} [opt] intCurIndex default shown position (from 1)
 * @param {int} [opt] intMin min shown position (from 1)
 * @param {int} [opt] intMax max shown position (from 1)
 * @param (int) [opt] intGroupSize
 */
function dynamic(strId, intCurIndex, intMin, intMax, intGroupSize){
    intMin = intMin || 1;
    intMax = intMax || 1;
    intCurIndex = intCurIndex || 1;
    
    this.obj = document.getElementById(strId);
    this.id = strId;
    this.groupSize = intGroupSize || 1;
    
    var list = dojo.query("div.item", this.obj);
    if (intCurIndex < 0) {
        var shownList = dojo.query("div.item:not(.hidden)", this.obj);
        if (shownList) {
            intCurIndex = shownList.length;
        }
    }
    this.currentIndex = (intCurIndex ? intCurIndex - 1 : 0);
    this.min = intMin - 1;
    this.max = (intMax < list.length) ? intMax - 1 : list.length - 1;
    
    list.forEach(function(item, idx){
        if (idx > this.currentIndex) {
            //dojo.removeClass(item,"hidden");
            dojo.addClass(item, "hidden");
        }
    }, this);
    
    this.Plus = function(){
        var hiddenList = dojo.query("div.item.hidden", this.obj)        
        if (hiddenList) {
            hiddenList.forEach(function(item, idx){
                if (idx <= this.max && idx < this.groupSize) {
                    dojo.removeClass(item, "hidden");
                }
            }, this);
			
			// is this.currentIndex used at all?
            this.currentIndex += (hiddenList.length < this.groupSize) ? hiddenList.length : this.groupSize;
			
            this.Show();
        }
    }
    this.Minus = function(){
        var shownList = dojo.query("div.item:not(.hidden)", this.obj);
        if (shownList) {
            var linesNum = Math.ceil(shownList.length / this.groupSize);
            var itemsNum = (linesNum - 1) * this.groupSize;

            shownList.forEach(function(item, idx){
                if (idx > this.min && idx > (itemsNum-1)) {
                    dojo.addClass(item, "hidden");
                }
            }, this);
            this.currentIndex -= (shownList.length < this.groupSize) ? shownList.length : this.groupSize;
            this.Show();
        }
    }
    this.Show = function(){
        /*if (this.obj){
         this.obj.style.height = this.obj.scrollHeight + 'px';
         }*/
        ADND.equalContainers();
        var shownList = dojo.query("div.item:not(.hidden)",this.obj);
        updateWidgetSize(this.id, (shownList.length > this.min ) ? shownList.length : this.min);
    }
    ADND.equalContainers();
}
function Dragger(){
    this.valuesLoaded = 0;
    this.clipboard;
    this.placeHolder;
    this.dragging = 0;
    this.resolving = 0;
    this.curX = 0;
    this.curY = 0;
    this.offX = 0;
    this.offY = 0;
    this.arrDragableItems = new Array();
    this.arrDragableItemsCoords = new Array();
    this.arrContainersCoords = new Array();
    this.Animation;
    this.calcCoords = function(obj){
        var objRes = {
            topCoord: 0,
            leftCoord: 0
        };
        var trigger = (obj && obj.parentNode);
        if (trigger) {
            objNextLevelCoords = this.calcCoords(obj.parentNode);
            objRes.leftCoord = obj.offsetLeft + objNextLevelCoords.leftCoord;
            objRes.topCoord = obj.offsetTop + objNextLevelCoords.topCoord;
        }
        return objRes;
    }
    
    this.loadValues = function(arrContainers){
        this.getDragableItems(arrContainers);
        this.getDragableItemsCoords();
        this.getContainersCoords();
    }
    
    this.getDragableItems = function(arrContainers){
        this.arrDragableItems = new Array();
        for (key in arrContainers) {
            var objContainter = document.getElementById(arrContainers[key]);
            if (objContainter) {
                for (key2 in objContainter.childNodes) {
                    if (objContainter.childNodes[key2] && objContainter.childNodes[key2].tagName == 'DIV') {
                        this.arrDragableItems.push(objContainter.childNodes[key2]);
                    }
                }
            }
        }
    }
    this.getDragableItemsCoords = function(){
        this.arrDragableItemsCoords = new Array();
        if (this.arrDragableItems.length) {
            for (key in this.arrDragableItems) {
                if (this.arrDragableItems[key].tagName != 'DIV') {
                    continue;
                }
                var objDragableItem = this.arrDragableItems[key];
                var arrCoords = new Array();
                var coords = this.calcCoords(objDragableItem);
                arrCoords['xTopLeft'] = coords.leftCoord;
                arrCoords['yTopLeft'] = coords.topCoord;
                arrCoords['xBottomRight'] = coords.leftCoord + objDragableItem.offsetWidth;
                if (this.getNext(objDragableItem)) {
                    arrCoords['yBottomRight'] = coords.topCoord + (this.getNext(objDragableItem).offsetTop - objDragableItem.offsetTop);
                }
                else {
                    arrCoords['yBottomRight'] = coords.topCoord + objDragableItem.offsetHeight;
                }
                arrCoords['object'] = objDragableItem;
                this.arrDragableItemsCoords.push(arrCoords);
            }
        }
    }
    this.getContainersCoords = function(){
        this.arrContainersCoords = new Array();
        if (arrContainers.length) {
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                var coords = this.calcCoords(objContainer);
                var arrCoords = new Array();
                arrCoords['xTopLeft'] = coords.leftCoord;
                arrCoords['yTopLeft'] = coords.topCoord;
                arrCoords['xBottomRight'] = coords.leftCoord + objContainer.offsetWidth;
                arrCoords['yBottomRight'] = coords.topCoord + objContainer.offsetHeight;
                arrCoords['object'] = objContainer;
                this.arrContainersCoords.push(arrCoords);
            }
        }
    }
    this.getCurMouseCoord = function(e){
        e = this.getEvent(e);
        if (e.pageX || e.pageY) {
            ADND.curX = e.pageX;
            ADND.curY = e.pageY;
        }
        else 
            if (e.clientX || e.clientY) {
                ADND.curX = e.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
                ADND.curY = e.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
            }
    }
    this.Drag = function(e, obj){
		if (getEventTarget(e).tagName == "A") {
			return true;
		}
        if (ADND.clipboard && ADND.placeHolder) {
            ADND.Animation.terminate(ADND.Animation);
        }
        if (!ADND.valuesLoaded && arrContainers) {
            this.loadValues(arrContainers);
            ADND.valuesLoaded = 1;
        }
        e = this.getEvent(e);
        if (obj && !this.dragging) {
            this.dragging = 1;
            this.clipboard = obj;
            this.getCurMouseCoord(e);
            var coords = this.calcCoords(ADND.clipboard);
            ADND.offX = ADND.curX - coords.leftCoord;
            ADND.offY = ADND.curY - coords.topCoord;
            this.placeHolder = document.createElement('div');
            this.placeHolder.className = 'placeHolder';
            this.placeHolder.style.width = (this.clipboard.offsetWidth - 2) + 'px';
            this.placeHolder.style.height = (this.clipboard.offsetHeight - 2) + 'px';
            this.placeHolder.style.display = 'none';
            this.clipboard.style.left = coords.leftCoord + 'px';
            this.clipboard.style.top = coords.topCoord + 'px';
            this.clipboard.style.position = "absolute";
            this.clipboard.parentNode.insertBefore(this.placeHolder, this.clipboard);
            this.clipboard.parentNode.removeChild(this.clipboard);
            document.body/*dojo.byId("home")*/.appendChild(this.clipboard);
            this.placeHolder.style.display = 'block';
            /*            if (document.width < e.clientX+obj.clientWidth-ADND.offX ||
             document.height < e.clientY+obj.clientHeight-ADND.offY ||
             0 > e.clientX-ADND.offX ||
             0 > e.clientY-ADND.offY) {
             ADND.Drop();
             return;
             }
             */
            this.bindClipboard();
        }
        document.onmouseup = ADND.Drop;
    }
    
    this.Drop = function(e, obj){
        ADND.dragging = 0;
        document.onmousemove = function(){
        };
        document.onmouseup = function(){
        };
        //document.onmouseout = function(){};
        
        ADND.Animation = new Animate(ADND.clipboard);
        var placeHolderCoords = ADND.calcCoords(ADND.placeHolder);
        ADND.Animation.setTargetPoint(placeHolderCoords.leftCoord, placeHolderCoords.topCoord);
        ADND.Animation.Run(behavior.line, ADND.DropComplete);
        
        //ADND.DropComplete(ADND.clipboard);
    }
    this.DropComplete = function(obj){
        ADND.clipboard = obj;
        if (ADND.clipboard) {
            ADND.clipboard.style.left = "";
            ADND.clipboard.style.top = "";
            ADND.clipboard.style.position = "relative";
        }
        ADND.placeHolder.parentNode.insertBefore(ADND.clipboard, ADND.placeHolder);
        ADND.placeHolder.parentNode.removeChild(ADND.placeHolder);
        ADND.clipboard = null;
        ADND.placeHolder = null;
        if (arrContainers.length) {
            var maxHeight = 0;
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                var DivObj;
                if (objContainer.lastChild && objContainer.lastChild.tagName == 'DIV') {
                    DivObj = objContainer.lastChild;
                }
                else {
                    DivObj = ADND.getPrev(objContainer.lastChild);
                }
                var height = 0;
                if (DivObj) {
                    height = DivObj.offsetTop + DivObj.offsetHeight;
                }
                else {
                    height = 0;
                }
                maxHeight = Math.max(maxHeight, height)
            }
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                objContainer.style.height = maxHeight + "px";
            }
        }
        ADND.valuesLoaded = 0;
        ADND.dragging = 0;
        updateWidgetsState(dojo.byId('home_container_1'), dojo.byId('home_container_2'));
    }
    
    this.Track = function(e){
        var posx = 0;
        var posy = 0;
        var e = ADND.getEvent(e);
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else 
            if (e.clientX || e.clientY) {
                posx = e.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
                posy = e.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
            }
        document.getElementById('coord').innerHTML = 'X = ' + posx + ', Y = ' + posy;
    }
    this.bindClipboard = function(){
        document.onmousemove = function(event){
            var posx = 0;
            var posy = 0;
            var e = ADND.getEvent(event);
            if (e.pageX || e.pageY) {
                posx = e.pageX;
                posy = e.pageY;
            }
            else {
                posx = e.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
                posy = e.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
            }
            ADND.curX = posx;
            ADND.curY = posy;
            ADND.clipboard.style.left = ADND.curX - ADND.offX + 'px';
            ADND.clipboard.style.top = ADND.curY - ADND.offY + 'px';
            ADND.resolveConflict(e);
        };
        //document.onmouseout = "fixOnMouseOut(document, event, 'ADND.Drop()')";
    }
    this.isAbovePlaceHolder = function(e){
        e = this.getEvent(e);
        var objDragableItem = this.placeHolder;
        var arrCoords = new Array();
        var coords = this.calcCoords(objDragableItem);
        arrCoords['xTopLeft'] = coords.leftCoord;
        arrCoords['yTopLeft'] = coords.topCoord;
        arrCoords['xBottomRight'] = coords.leftCoord + objDragableItem.offsetWidth;
        arrCoords['yBottomRight'] = coords.topCoord + objDragableItem.offsetHeight;
        arrCoords['object'] = objDragableItem;
        var result = this.isInBox(arrCoords, e)
        return result;
    }
    this.resolveConflict = function(e){
        e = this.getEvent(e);
        if (!ADND.dragging) {
            return false;
        }
        if (!ADND.valuesLoaded && arrContainers) {
            this.loadValues(arrContainers);
            ADND.valuesLoaded = 1;
        }
        ADND.resolving = 1;
        if (this.isAbovePlaceHolder(e)) {
            return false;
        }
        for (key in this.arrDragableItemsCoords) {
            var arrCoordsToCheck = this.arrDragableItemsCoords[key];
            
            if (arrCoordsToCheck['object'] == ADND.clipboard) {
                continue;
            }
            var arrConflict = this.isInBox(arrCoordsToCheck, e);
            if (arrConflict && ADND.placeHolder && ADND.placeHolder.parentNode) {
                var objConflictItem = arrConflict['object'];
                if (arrConflict['position'] == 'before') {
                    if (this.getPrev(objConflictItem) != ADND.placeHolder) {
                        objConflictItem.parentNode.insertBefore(ADND.placeHolder, objConflictItem);
                        ADND.valuesLoaded = 0;
                    }
                    ADND.resolving = 0;
                }
                else 
                    if (arrConflict['position'] == 'after') {
                        /* insert after */
                        var next = this.getNext(objConflictItem);
                        if (next && next != ADND.placeHolder) {
                            objConflictItem.parentNode.insertBefore(ADND.placeHolder, next);
                            ADND.valuesLoaded = 0;
                        }
                        else 
                            if (!next) {
                                objConflictItem.parentNode.appendChild(ADND.placeHolder);
                                ADND.valuesLoaded = 0;
                            }
                        ADND.resolving = 0;
                    }
                    else {
                        ADND.resolving = 0;
                    }
            }
        }
        if (ADND.resolving == 1) {
            for (key in this.arrContainersCoords) {
                var arrCoordsToCheck = this.arrContainersCoords[key];
                var arrConflict = this.isInBox(arrCoordsToCheck, e);
                if (arrConflict && ADND.placeHolder && ADND.placeHolder.parentNode) {
                    var objConflictItem = arrConflict['object'];
                    ADND.placeHolder.parentNode.removeChild(ADND.placeHolder);
                    objConflictItem.appendChild(ADND.placeHolder);
                    ADND.resolving = 0;
                }
            }
        }
        if (arrContainers.length) {
            var maxHeight = 0;
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                var DivObj;
                if (objContainer.lastChild && objContainer.lastChild.tagName == 'DIV') {
                    DivObj = objContainer.lastChild;
                }
                else {
                    DivObj = ADND.getPrev(objContainer.lastChild);
                }
                var height = 0;
                if (DivObj) {
                    height = DivObj.offsetTop + DivObj.offsetHeight;
                }
                else {
                    height = 0;
                }
                maxHeight = Math.max(maxHeight, height)
            }
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                objContainer.style.height = maxHeight + "px";
            }
        }
        ADND.resolving = 0;
    }
    this.isInBox = function(arrCords, e){
        e = this.getEvent(e);
        var arrReturn = new Array();
        this.getCurMouseCoord(e);
        if ((this.curX > arrCords['xTopLeft']) && (this.curX < arrCords['xBottomRight']) &&
        (this.curY > arrCords['yTopLeft']) &&
        (this.curY < arrCords['yBottomRight'])) {
            if (this.curY < (arrCords['yBottomRight'] + (arrCords['yTopLeft'] - arrCords['yBottomRight']) * 0.45)) {
                arrReturn['position'] = 'before';
            }
            else 
                if (this.curY > (arrCords['yBottomRight'] + (arrCords['yTopLeft'] - arrCords['yBottomRight']) * 0.45)) {
                    arrReturn['position'] = 'after';
                }
                else {
                    arrReturn['position'] = 'keep';
                }
            arrReturn['object'] = arrCords['object'];
            return arrReturn;
        }
        else {
            return null;
        }
    }
    this.getNext = function(obj){
        if (!obj.nextSibling) {
            return null;
        }
        if (obj.nextSibling.tagName == 'DIV') {
            return obj.nextSibling
        }
        return this.getNext(obj.nextSibling);
    }
    this.getPrev = function(obj){
        if (!obj || !obj.previousSibling) {
            return null;
        }
        if (obj.previousSibling.tagName == 'DIV') {
            return obj.previousSibling
        }
        return this.getPrev(obj.previousSibling);
    }
    this.PD = function(obj){
        var strOut = '';
        for (key in obj) {
            strOut += key + ':' + obj[key] + '<br/>';
        }
        document.getElementById('conf').innerHTML = strOut;
    }
    this.getEvent = function(e){
        var evt = e || window.event;
        return evt;
    }
    this.equalContainers = function(){
        if (arrContainers.length) {
            var maxHeight = 0;
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                var DivObj;
                if (objContainer.lastChild && objContainer.lastChild.tagName == 'DIV') {
                    DivObj = objContainer.lastChild;
                }
                else {
                    DivObj = ADND.getPrev(objContainer.lastChild);
                }
                var height = 0;
                if (DivObj) {
                    height = DivObj.offsetTop + DivObj.offsetHeight;
                }
                else {
                    height = 0;
                }
                maxHeight = Math.max(maxHeight, height)
            }
            for (key in arrContainers) {
                var objContainer = document.getElementById(arrContainers[key]);
                objContainer.style.height = maxHeight + "px";
            }
        }
    }
}

var arrContainers = new Array();
var ADND = new Dragger();


function Animate(obj){
    this.clipboard = obj;
    this.onComplete;
    this.state = {
        currentX: 0,
        currentY: 0,
        targetX: 0,
        targetY: 0,
        speed: 1,
        angle: new objAngle,
        steps: 0,
        fps: 12
    }
    this.behavior;
    this.interval;
    this.calcCoords = function(obj){
        var objRes = {
            topCoord: 0,
            leftCoord: 0
        };
        var trigger = (obj && obj.parentNode);
        if (trigger) {
            objNextLevelCoords = this.calcCoords(obj.parentNode);
            objRes.leftCoord = obj.offsetLeft + objNextLevelCoords.leftCoord;
            objRes.topCoord = obj.offsetTop + objNextLevelCoords.topCoord;
        }
        return objRes;
    }
    this.setTargetPoint = function(intX, intY){
        this.state.targetX = intX;
        this.state.targetY = intY;
    }
    this.setExtra = function(arrExtra){
    
    }
	this.terminate = function(obj){
		 singletoneTM.finishThread(obj.interval);
         obj.onComplete(obj.clipboard);
	}
    this.calculateNextPoint = function(obj){
        if (obj.behavior.stopCase(obj.state)) {
            singletoneTM.finishThread(obj.interval);
            obj.onComplete(obj.clipboard);
        }
        else {
            obj.state.angle.updateSpeed(obj.state.speed);
            obj.state.currentX += obj.state.angle.deltaX;
            obj.state.currentY += obj.state.angle.deltaY;
            obj.setCoords(obj.state.currentX, obj.state.currentY);
            obj.behavior.updateState(obj.state);
            obj.state.steps++;
        }
    }
    this.Run = function(objBehavior, onComplete){
        this.behavior = objBehavior;
        this.behavior.acceleration = 0;
		this.behavior.distToTarget = 0;
        this.state.speed = 10;
        this.onComplete = onComplete;
        //this.interval = setInterval("ADND.Animation.calculateNextPoint()", 1000 / this.state.fps);
        this.interval = singletoneTM.addThread(this.calculateNextPoint, this);
        singletoneTM.startInterval();
    }
    this.setCoords = function(x, y){
        this.clipboard.style.display = 'none';
        this.clipboard.style.left = x + 'px';
        this.clipboard.style.top = y + 'px';
        this.clipboard.style.display = 'block';
    }
    var Coords = this.calcCoords(this.clipboard);
    this.state.currentX = Coords.leftCoord;
    this.state.currentY = Coords.topCoord;
    if (this.clipboard.parentNode != document.body) {
        this.clipboard.style.left = this.currentX + 'px';
        this.clipboard.style.top = this.currentY + 'px';
        this.clipboard.style.position = "absolute";
        this.clipboard.parentNode.removeChild(this.clipboard);
        document.body.appendChild(this.clipboard);
    }
}

var behavior = {
	blank: {
		updateState: function(state){},
        stopCase: function(state){
        	return true;
        }
	},
    line: {
		stopDist : 5,
        distToTarget: 0,
        accelerationP: 0,
        accelerationM: 0,
        updateState: function(state){
            var deltaY = state.targetY - state.currentY;
            var deltaX = state.targetX - state.currentX;
            state.angle.dX = deltaX;
            state.angle.dY = deltaY;
            this.distToTarget = state.angle.getDist();
            this.accelerationP = 2;
			this.accelerationM = Math.sqrt(this.distToTarget / 300);
			state.speed *= this.accelerationM;
			state.speed += this.accelerationP;
        },
        stopCase: function(state){
            if (this.distToTarget == 0 ) {
                this.updateDist(state);
            }
            if ((this.distToTarget < this.stopDist) || (state.steps > 100)) {
                return true;
            }
            else {
                return false;
            }
        },
        updateDist: function(state){
            var deltaY = state.targetY - state.currentY;
            var deltaX = state.targetX - state.currentX;
            this.distToTarget = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
        }
    },
	spiral: {
		stopDist : 5,
        distToTarget: 0,
        accelerationP: 0,
        accelerationM: 0,
        updateState: function(state){
            var deltaY = state.targetY - state.currentY;
            var deltaX = state.targetX - state.currentX;
            state.angle.dX = deltaX;
            state.angle.dY = deltaY;
            this.distToTarget = state.angle.getDist();
            this.accelerationP = 2;
			this.accelerationM = Math.sqrt(this.distToTarget / 300);
			state.angle.rotationAng = Math.min(100 / this.distToTarget , 0.9) ;
			state.speed *= this.accelerationM;
			state.speed += this.accelerationP;
        },
        stopCase: function(state){
            if (this.distToTarget == 0 ) {
                this.updateDist(state);
            }
            if ((this.distToTarget < this.stopDist) || (state.steps > 100)) {
                return true;
            }
            else {
                return false;
            }
        },
        updateDist: function(state){
            var deltaY = state.targetY - state.currentY;
            var deltaX = state.targetX - state.currentX;
            this.distToTarget = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
        }
    }
}
function objAngle(){
    this.dX = 0;
    this.dY = 0;
    this.rotationAng = 0;
    this.deltaX = 0;
    this.deltaY = 0;
    this.getDist = function(){
        return Math.sqrt(Math.pow(this.dX, 2) + Math.pow(this.dY, 2));
    }
    this.updateSpeed = function(speed){
        // cos(a) = (this.dX / this.getDist())
        // sin(a) = (this.dY / this.getDist())
        // sin(a+b) = sin(a) * cos(b) + cos(a) * sin(b)
        // cos(a+b) = cos(a) * cos(b) - sin(a) * sin(b)
        if (this.getDist() != 0) {
            var cosA = (this.dX / this.getDist());
            var sinA = (this.dY / this.getDist());
        }
        else {
            var cosA = 0;
            var sinA = 0;
        }
        this.deltaX = speed * (cosA * Math.cos(this.rotationAng) - sinA * Math.sin(this.rotationAng));
        this.deltaY = speed * (sinA * Math.cos(this.rotationAng) + cosA * Math.sin(this.rotationAng));
    }
}
var img_padding = 5; // margin etc...
dojo.require("dojo.NodeList-fx");
dojo.require("dojox.fx.ext-dojo.NodeList");
var sliding = false;
var Fchanged = false;
var img_ids = ["ig0", "ig1", "ig2", "ig3", "ig4", "ig5", "ig6"];
var img_cur = 3; // position of the cur img in img_ids (zero based)
var img_size;
// offs is the offset relative to img_cur into img_ids
function setImgId(node, offs){
    if (img_cur + offs >= 0 && img_cur + offs < img_ids.length) {
        if (node.id != img_ids[img_cur + offs]) {
            node.id = img_ids[img_cur + offs];
            dojo.attr(dojo.query("img", node)[0], "src", "");
            dojo.attr(dojo.query(".photo_name_inner", node)[0], "id", "imageName" + node.id);
            dojo.query(".photo_name_inner", node)[0].innerHTML = '';
        }
        node.style.visibility = 'visible';
    }
    else {
        if (offs == 1) {
            dojo.byId('photo_next').style.visibility = 'hidden';
        }
        else 
            if (offs == -1) {
                dojo.byId('photo_prev').style.visibility = 'hidden';
            }
        node.id = "";
        dojo.attr(dojo.query(".photo_name_inner", node)[0], "id", "");
        dojo.query(".photo_name_inner", node)[0].innerHTML = '';
        dojo.attr(dojo.query("img", node)[0], "src", "");
        dojo.query("img", node)[0].style.display = 'none';
        node.style.visibility = 'hidden';
    }
}


function setImgSrc(node){
    if (node.id) {
        var img = dojo.query("img", node)[0];
        img.style.visibility = "hidden";
        dojo.removeClass(dojo.query(".photo_img", node)[0], "photo_img_in_proc");
        dojo.removeClass(dojo.query(".photo_img", node)[0], "photo_img_no_sup");
        dojo.attr(img, "src", "");
        dojo.attr(img, "src", "ImageController.do?fileID=" + node.id + "&operation=galleryPhotoView");
        
        var width = img_size[node.id].width;
        var height = img_size[node.id].height;
        img.style.left = (img.parentNode.offsetWidth - width) / 2 + "px";
        img.style.top = (img.parentNode.offsetHeight - height) / 2 + "px";
        img.style.visibility = 'visible';
        img.style.display = 'block';
        
        node.style.visibility = 'visible';
    }
}

function getCurEditPhotoNode(){
    return dojo.byId(img_ids[img_cur].toString());
}

function editPhotoApplyState(node){
    if (dojo.byId('imageState') && dojo.byId('imageState').value == "processing") {
        dojo.addClass(dojo.query(".photo_img", node)[0], "photo_img_in_proc");
    }
    else 
        if (dojo.byId('imageState') && dojo.byId('imageState').value == "failed") {
            dojo.addClass(dojo.query(".photo_img", node)[0], "photo_img_no_sup");
        }
}

function editPhotoInit(){
    var photos = dojo.query("div#view_photo_container div.viewphoto");
    var width = photos[2].offsetWidth + img_padding * 2;
    dojo.byId("view_photo_container").style.width = 5 * width + "px";
    dojo.byId("view_photo_container").style.left = -(5 * width - dojo.byId("view_photo_window").clientWidth + img_padding) / 2 + "px";
    for (var photo = 0; photo < 5; photo++) {
        photos[photo].style.left = width * photo + img_padding + "px";
        setImgId(photos[photo], photo - 2);
    }
    //init the clicking placeholders - they got the same css
    dojo.byId("photo_prev").style.left = photos[1].style.left;
    dojo.byId("photo_next").style.left = photos[3].style.left;
    
    // load images in the specific order
    setImgSrc(photos[2]);
    setImgSrc(photos[3]);
    setImgSrc(photos[1]);
}

function switch_img(clicked){
	if(Fchanged){
		savePhoto();
		Fchanged = false;
	}
    if (sliding) 
        return;
    sliding = true;
    var photos = dojo.query("div#view_photo_container div.viewphoto");
    var w = photos[2].offsetWidth + img_padding * 2;
    var slide_by = 0;
    if (clicked == 1 && img_cur > 0) {
        --img_cur;
        photos[4].style.left = -w + img_padding + "px";
        dojo.place(photos[4], photos[0], "before");
        setImgId(photos[4], -2);
        setImgSrc(photos[0]);
        slide_by = w;
    }
    else 
        if (clicked == 3 && img_cur < img_ids.length - 1) {
            ++img_cur;
            photos[0].style.left = 5 * w + img_padding + "px";
            dojo.place(photos[0], photos[4], "after");
            setImgId(photos[0], 2);
            setImgSrc(photos[4]);
            slide_by = -w;
        }
    if (slide_by == 0) {
        sliding = false;
    }
    else {
        if (img_cur == 0) {
            dojo.byId('photo_prev').style.visibility = 'hidden';
        }
        if (img_cur == img_ids.length - 1) {
            dojo.byId('photo_next').style.visibility = 'hidden';
        }
        dojo.byId((slide_by > 0) ? 'photo_next' : 'photo_prev').style.visibility = 'visible';
        
        photos.slideBy({
            left: slide_by,
            onEnd: function(){
                sliding = false;
            }
        }).play();
    }
    updateImageDetails(img_ids[img_cur]);
}

function showImage(obj){
    obj.style.visibility = 'visible';
    obj.style.display = 'block';
}
function startFlashVideo(file_url) {
	     document.title = "VUFONE";
	    /*
	     * flashembed places Flowplayer into HTML element 
	     * whose id="example" (see below this script tag)
	     */
	    flashembed("video_obj", 
			/*
			* second argument supplies standard Flash parameters.
			* basically these are all you want to modify
			* but you can see full list here
			*/
			{
				// test that this swf- file can be accessed with your browser
				src:'images0906031041/videos/FlowPlayerLight.swf',
				width:444,  
				height:370,
				bgcolor:'#ffffff'
			}, {config: {   
			/*
			* third argument is Flowplayer specific configuration
			* full list of options is given here
			*/
				videoFile: file_url,
				initialScale: 'scale',
				
				// you can supply more options by separating them with commas
				useNativeFullScreen: true,
				loop: false,
				menuItems: [ true, true, true, true, false, false ] 
			}} );
};function TManager(){
    this.interval;
    this.startInterval = function(){
        this.interval = setInterval('RunThreads()', 1000 / 128);
    }
    this.endInterval = function(){
        for (key in this.arrThreads) {
            if (this.arrThreads[key]) {
                return;
            }
        }
        clearInterval(this.interval);
    }
    this.arrThreads = new Array();
    this.addThread = function(funcToStore, obj){
        var key = this.createThreadKey();
        if (!this.arrThreads[key]) {
            this.arrThreads[key] = new Array();
            this.arrThreads[key]['function'] = funcToStore;
            this.arrThreads[key]['object'] = obj;
            return key;
        }
    }
    this.runThreads = function(){
        for (key in this.arrThreads) {
            if (this.arrThreads[key]) {
                this.arrThreads[key]['function'](this.arrThreads[key]['object']);
            }
        }
    }
    this.finishThread = function(key){
        if (this.arrThreads[key]) {
            this.arrThreads[key] = null;
        }
        this.endInterval();
    }
    this.createThreadKey = function(){
        return this.randomString(10);
    }
    this.randomString = function(iLen){
        var sChrs = 'qwertyuiopasdfghjklzxcvbnm';
        var sRnd = '';
        for (var i = 0; i < iLen; i++) {
            var randomPoz = Math.floor(Math.random() * sChrs.length);
            sRnd += sChrs.substring(randomPoz, randomPoz + 1);
        }
        return sRnd;
    }
}

var singletoneTM = new TManager();

function RunThreads(){
    singletoneTM.runThreads();
}
function tabCloseOpen(iconNode){
    var objToShowHide = dojo.query(' .content', getAncestorWithClass(iconNode, 'widget'))[0];
    if (objToShowHide && objToShowHide.style) {
        var state;
        var display
        if (objToShowHide.style.display == 'none') {
            state = 'hidden';
            display = 'block';
        }
        else {
            display = 'none';
            state = 'shown';
        }
        objToShowHide.style.display = display;
        if (iconNode) {
            if (state == 'shown') {
                dojo.addClass(iconNode.parentNode.parentNode, 'collapsed');
                dojo.removeClass(iconNode, 'open');
                dojo.addClass(iconNode, 'close');
                updateWidgetState(objToShowHide.parentNode.id, 'none');
                dojo.query(' .PMControls', getAncestorWithClass(iconNode, 'widget')).style("display", "none");
            }
            else {
                dojo.removeClass(iconNode.parentNode.parentNode, 'collapsed');
                dojo.removeClass(iconNode, 'close');
                dojo.addClass(iconNode, 'open');
                updateWidgetState(objToShowHide.parentNode.id, 'block');
                dojo.query(' .PMControls', getAncestorWithClass(iconNode, 'widget')).style("display", "block");
            }
        }
    }
    ADND.equalContainers();
}

var DD;
var globalPostLoadFlags = {
    popSystemMessage: false
};
var globalPostLoad = function(){
    if (globalPostLoadFlags.popSystemMessage) {
        popSystemMessage();
    }
    var node = dojo.byId("tab_label_" + currentPage);
    //getAncestorWithClass(getEventTarget(e), 'tab');
    var tabs = getAncestorWithClass(node, 'tabs');
    dojo.query(".tab", tabs || dojo.query("#header .tabs")[0]).removeClass("active");
    if (tabs) {
        dojo.addClass(node, 'active');
    }
    
    globalPostLoadFlags.popSystemMessage = false;
}

function loadPageByHash(func){
	if(!func || func.length == 0){
		return false;
	}
    if (func.indexOf("-") > 0) {
        param = func.slice(func.indexOf("-") + 1);
        func = func.slice(0, func.indexOf("-"));
        var ev = func + "('" + param + "')";
    }
    else {
        var ev = func + '()';
    }
    try {
        eval(ev);
        return true;
    } 
    catch (e) {
        return false;
    }    
}

window.onload = function(){
    globalPostLoadFlags.popSystemMessage = true;
    initHistory('HomeDataController.do');
    DD = new dynamics();
    var func;
    if (window.location.hash.indexOf("#") >= 0) {
        func = window.location.hash.slice(window.location.hash.indexOf("#") + 1);
    }
    else 
        if (dojo.cookie('pageToLoad')) {
            func = dojo.cookie('pageToLoad');
            dojo.cookie('pageToLoad', '',{ expires: 0,path: '/' });
        }
    if (!loadPageByHash(func)) {
        loadLandingPage();
    }
    var selfNameNode = dojo.query("#sidebar_vcard .name");
    if (selfNameNode && dojo.trim(selfNameNode[0].innerHTML).length < 1) {
        loadProfile();
    }
}

function loadLandingPage(){
    document.title = "VUFONE";
    
    switch (COS.landing) {
        case "home":
            loadHome();
            break;
        case "contacts":
            
            loadContacts();
            break;
        case "calendar":
            loadCalendar();
            break;
        case "photos":
            loadPhotos();
            break;
        case "video":
            loadVideos();
            break;
        case "music":
            loadAudios();
            break;
        case "documents":
            loadDocuments();
            break;
        case "messages":
            loadMessages();
            break;
        default:
            loadHome();
            break;
    }
}

function dynamics(){
    //this.updates_dynamic_content = new dynamic('updates_dynamic_content', Array(96, 173, 256));
    if (dojo.byId('calendar_dynamic_content')) {
        this.calendar_dynamic_content = new dynamic('calendar_dynamic_content', -1, 3, 30);
    }
    if (dojo.byId('tasks_dynamic_content')) {
        this.tasks_dynamic_content = new dynamic('tasks_dynamic_content', -1, 3, 30);
    }
    if (dojo.byId('messages_dynamic_content')) {
        this.messages_dynamic_content = new dynamic('messages_dynamic_content', -1, 3, 30);
    }
    if (dojo.byId('documents_dynamic_content')) {
        this.documents_dynamic_content = new dynamic('documents_dynamic_content', -1, 3, 30);
    }
    if (dojo.byId('contact_dynamic_content')) {
        this.contact_dynamic_content = new dynamic('contact_dynamic_content', -1, 3, 30);
    }
    if (dojo.byId('photos_dynamic_content')) {
        this.photos_dynamic_content = new dynamic('photos_dynamic_content', -1, 4, 32, 4);
    }
    if (dojo.byId('video_dynamic_content')) {
        this.video_dynamic_content = new dynamic('video_dynamic_content', -1, 4, 32, 4);
    }
    if (dojo.byId('music_dynamic_content')) {
        this.music_dynamic_content = new dynamic('music_dynamic_content', -1, 3, 30);
    }
    //this.ringtones_dynamic_content = new dynamic('ringtones_dynamic_content', Array(60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320));
    if (dojo.byId('sidebar_actions_content')) {
        this.sidebar_actions_content = new dynamic('sidebar_actions_content', -1, 2, 10);
    }
    //this.sidebar_faq_content = new dynamic('sidebar_faq_content', Array(85, 116, 147, 178, 207));
}

function updateWidgetsState(leftConteiner, rightConteiner){
    var left = dojo.byId(leftConteiner);
    var right = dojo.byId(rightConteiner);
    var leftContent = new Array();
    var rightContent = new Array();
    dojo.query(".dragable", left).forEach(function(widget){
        leftContent[leftContent.length] = widget.id;
    });
    dojo.query(".dragable", right).forEach(function(widget){
        rightContent[rightContent.length] = widget.id;
    });
    var uri = 'UserSettingsController.do';
    var post = {
        action: 'saveWidgetsPosition',
        leftColumn: leftContent,
        rightColumn: rightContent
    };
    LoadData(uri, null, post, null);
    
}

var table = new Array();
table['contact_dynamic_content'] = 'home_contacts';
table['photos_dynamic_content'] = 'home_photos';
table['video_dynamic_content'] = 'home_videos';
table['music_dynamic_content'] = 'home_audios';
table['calendar_dynamic_content'] = 'home_calendar';
table['messages_dynamic_content'] = 'home_messages';
table['sidebar_actions_content'] = 'sidebar_actions';
table['tasks_dynamic_content'] = 'home_tasks';
table['documents_dynamic_content'] = 'home_documents';
function updateWidgetSize(widgetID, size){
    var widget = table[widgetID];
    var uri = 'UserSettingsController.do';
    var post = {
        action: 'saveWidgetSize',
        widgetID: widget,
        widgetSize: size
    };
    LoadData(uri, null, post, null);
}

function updateWidgetState(widget, state){
    var uri = 'UserSettingsController.do';
    var post = {
        action: 'saveWidgetState',
        widgetID: widget,
        widgetState: state
    };
    LoadData(uri, null, post, null);
}

function loadHome(){
    var extra = {
        postLoad: function(){
            if (versionIE() == 6) {
                dojo.query(".dragable .top .title").forEach(function(item){
                    item.onmousedown = null;
                });
                dojo.query(".dragable .top").style('cursor', 'default');
            }
            currentPage = 'home';
            hideFlash();
            if (dojo.byId('home_container_1')) {
                arrContainers[0] = 'home_container_1';
            }
            if (dojo.byId('home_container_2')) {
                arrContainers[1] = 'home_container_2';
            }
            DD = new dynamics();
        }
    };
    LoadData('HomeDataController.do', 'content', null, extra, null, 'loadHome');
}

function showPlaceHolderForPhoto(event, obj){
    obj.src = 'images0906031041/photos/bg-pic-no-sup-lit.png';
}

function showPlaceHolderForVideo(event, obj){
    obj.src = 'images0906031041/videos/bg-video-no-sup-lit.png';
}

var wizardMinimized = false;
function minimizeWizard(){
    dojo.query('#wizard .full')[0].style.display = 'none';
    dojo.query('#wizard .minimized')[0].style.display = 'block';
    dojo.query('#wizard .minimized .flash')[0].style.visibility = 'visible';
    wizardMinimized = true;
    stopWizardPolling();
    placeAudioPlayer();
    document.title = "VUFONE";
}

function maximizeWizard(){
    dojo.query('#wizard .minimized')[0].style.display = 'none';
    dojo.query('#wizard .full')[0].style.display = 'block';
    dojo.query('#wizard .full .flash')[0].style.visibility = 'visible';
    wizardMinimized = false;
    initWizardPolling();
    placeAudioPlayer();
    document.title = "VUFONE";
}

var wizardPollingCount = 0;
var wizardInterval;
var currentFlash = '';

function getWizardState(){
    var extra = {
        postLoad: function(){
            var userState = commonJson.userState;
            if (!commonJson.flashSrc || commonJson.flashSrc == '') {
                dojo.byId('wizard').style.display = 'none';
                stopWizardPolling();
                return;
            }
            var newFlashSrc = "/" + commonJson.flashSrc + ".swf";
            if (currentFlash != commonJson.flashSrc) {
                var flash = getFlashMovie('wizardFlash');
                var oldSrc = getFlashSrc(flash);
                var regExp = new RegExp("/([^\\./]*)\\.[^\\./]+$");
                var results = oldSrc.match(regExp);
                if (!results || results[0] != newFlashSrc) {
                    var newFlashSrc = oldSrc.replace(regExp, newFlashSrc);
                    setFlashSrc(flash, newFlashSrc);
                    currentFlash = commonJson.flashSrc;
                    dojo.query('#wizard .full')[0].style.display = 'none';
                    dojo.query('#wizard .full')[0].style.display = 'block';
                }
            }
            //manageWizardPolling();
        }
    };
    LoadData('WizardDataController.do', null, null, extra, true);
}

function manageWizardPolling(){
    wizardPollingCount++;
    if (wizardPollingCount > 100) {
        stopWizardPolling();
    }
}

function initWizardPolling(time){
    if (!time) {
        time = 10;
    }
    
    wizardInterval = window.setInterval(getWizardState, time * 1000);
    document.title = "VUFONE";
}

function stopWizardPolling(){
    window.clearInterval(wizardInterval);
    document.title = "VUFONE";
}

var isIE = navigator.appName.indexOf("Microsoft") != -1;
function getFlashMovie(movieName){
    var list = (isIE) ? window[movieName] : document[movieName];
    if (isIE) {
        return list;
    }
    else {
        for (id in list) {
            if (list[id].tagName == 'EMBED') {
                return list[id];
            }
        }
    }
}

function getFlashSrc(obj){
    if (isIE) {
        return obj.object.movie;
    }
    else {
        return obj.src;
    }
}

function setFlashSrc(obj, src){
    if (isIE) {
        obj.object.movie = src;
    }
    else {
        obj.src = src;
    }
}

/** flash interface
 *
 * these functions will be called from wizard flash
 */
function sendTextLink(){
    var params = {
        action: 'sendWapPushAsText'
    };
    LoadData('WizardDataController.do', null, params, null, true);
}

function sendWapPush(){
    performAction('getAgent');
}

function closeWizard(){
    var params = {
        action: 'closeActivationWizard'
    };
    var extra = {
        postLoad: function(){
            getWizardState();
        }
    };
    LoadData('WizardDataController.do', null, params, extra, true);
}

/**
 * contact us
 */
function loadContactUs(){
    var extra = {
    };
    LoadData('InnerContactUsController.do', 'content', null, extra, null, 'loadContactUs');
}

/**************validation  of contact us form************************/

function sendInnerContactUs(){
     var formId = "contact_us_form";

     /** check  fields , contain content ?**/
 
 

    
     var params = dojo.formToObject(formId);
  if (params.subject.length == 0) {
        popUpDialog('notice', jsLocaleBundle["JS.CONTACT_US.EMPTY_INPUT.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"]);
        return;
    }
     /** check all  input fields , contain content ?**/
    if (params.text.length == 0) {
        popUpDialog('notice', jsLocaleBundle["JS.CONTACT_US.EMPTY_INPUT.MSG"], jsLocaleBundle["JS.POPUP.TITLE.ATTENTION"]);
        return;
    }
  
    var extra = {
        postLoad: function(resp){
               
              	  dojo.byId('border_in').innerHTML = resp;
                
        }
    };
    LoadData('InnerContactUsController.do', null, params, extra, true);
        
}

/************************* check subject themes**************************/
function themes_subject(){
     var objSubject = dojo.byId('select_subject');
    var strSubject = objSubject.options[objSubject.selectedIndex].value;
    
    if (strSubject.length > 0 && strSubject=='Other' ) {
        dojo.byId('contact_us_input_subject').style['display'] ='block';
        dojo.byId('contact_us_input_select').style['display'] = 'none';
    }else {
           dojo.byId('subject').value = strSubject;
    }
}
/************************ end  check subject themes****************************/

