if(typeof(DEBUG_BY_IP) == 'undefined'){ DEBUG_BY_IP = false; } function show_picture(script, src, alt, width, height) { if(src.indexOf('__gen=1|') > 0){ if((script.substring(0,7).toLowerCase()) != "http://" && (script.substring(0,8).toLowerCase() != "https://")){ script = frontBaseHref + script; } script = script + '?' + src; }else{ script = src; } if(aMatches = script.match(/\.swf$/i)){ AMI.UI.MediaBox.open(decodeURIComponent(script), width, height); }else{ AMI.UI.MediaBox.open(decodeURIComponent(script)); } return; } function show_details(script) { if ( (script.substring(0,7).toLowerCase()) != "http://" && (script.substring(0,8).toLowerCase() != "https://" ) ){ script = frontBaseHref + script; } var w_width = 200; var w_height = 250; if (w_height > window.screen.availHeight) w_height = window.screen.availHeight; if (w_width > window.screen.availWidth) w_width = window.screen.availWidth; window.open(script, "pic", "resizable=yes, status=yes, scrollbars=yes, width=" + w_width + ", height=" + w_height); //return false; } function none(){ return false; } function isEmail(string) { // if (string.search(/^(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+(;|,|$))+$/) != -1) if (string.search(/^(\w+[\w.-]*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+(;|,|$))+$/) != -1) return true; else return false; } // // following functions will be deleted later // function collect_link(cform){ var vlink = ''; var first = 1; for(var i=0; i= 0){ content = content.substr(cartStatusPos); amiSession.loadVariables(); var aVarNames = content.split('|'); amiCart.updateBlock(aVarNames[1], aVarNames[2]); var actionStatus = ''; for(i = 3; i < aVarNames.length; i++){ actionStatus += (i > 3 ? '|' : '') + aVarNames[i]; } if(typeof(onAddedToCartMessage) == 'function'){ onAddedToCartMessage(actionStatus); }else{ alert(actionStatus); } } }, updateBlock: function(itemCountCookieName, totalCookieName){ var cartItemCount = amiSession.get(itemCountCookieName); if(document.getElementById('idEshopCartIsNotEmpty')){ document.getElementById('idEshopCartIsNotEmpty').style.display = (cartItemCount == '' || cartItemCount == 0 ? 'none' : 'block'); } if(document.getElementById('idEshopCartIsEmpty')){ document.getElementById('idEshopCartIsEmpty').style.display = (cartItemCount == '' || cartItemCount == 0 ? 'block' : 'none'); } if(cartItemCount != ''){ if(document.getElementById(itemCountCookieName)){ document.getElementById(itemCountCookieName).innerHTML = cartItemCount; } if(document.getElementById(totalCookieName)){ document.getElementById(totalCookieName).innerHTML = amiSession.get(totalCookieName); } if(document.getElementById('eshopCartEmpty')){ document.getElementById('eshopCartEmpty').style.display = (cartItemCount > 0 ? 'inline' : 'none'); } } if(typeof(onUpdateCartBlock) == 'function'){ // backward compatibility onUpdateCartBlock(cartItemCount, amiSession.get(totalCookieName)); }else if(typeof(this.onUpdateBlock) == 'function'){ this.onUpdateBlock(cartItemCount, amiSession.get(totalCookieName)); } } } /* backward compatibility { */ // @todo replace AddToCart by amiCart.add and delete this function function AddToCart(url, itemId, numPrice, wrongPriceMsg){ return amiCart.add(url, itemId, numPrice, wrongPriceMsg); } // @todo replace AddToCartProp by amiCart.addProp and delete this function function AddToCartProp(url, itemId, propId, numPrice){ return amiCart.addProp(url, itemId, propId, numPrice); } /* } backward compatibility */ /* ADVERTISING BLOCK */ var advCurTmStamp = new Date(); document.usedAdvData = ""; var isInnerHtmlSupported = -1; var shownAdvPlaces = ''; var shownAdvPlacesCnt = 0; var advReferrer = '' var advPlaceCnts = new Array(); if(document.referrer) advReferrer = document.referrer; function processShownAdvPlaces(shownAdvPlaces){ counter = 0; pos = -1; res = ""; while((pos = shownAdvPlaces.indexOf(';', pos+1)) >= 0){ if((pos1 = shownAdvPlaces.indexOf(';', pos+1)) < 0) pos1 = shownAdvPlaces.length; if(pos1-pos-1 > 0){ curAdvPlace = shownAdvPlaces.substr(pos+1, pos1-pos-1); if((cpos = curAdvPlace.indexOf('_')) >= 0){ counter = curAdvPlace.substr(cpos+1)-1; curAdvPlace = curAdvPlace.substr(0, cpos); } advPlaceCnts[curAdvPlace] = ++counter; res += ';'+curAdvPlace+"_"+counter; } } if(res.length > 0) res += ';'; return res; } function showAdvPlace(idPlace, viewURL){ if(isInnerHtmlSupported == -1){ if(document.body.innerHTML) isInnerHtmlSupported = 1; else isInnerHtmlSupported = 0; } // After the document is loaded (new scheme) if(isInnerHtmlSupported == 1){ shownAdvPlacesCnt ++; document.write(''); shownAdvPlaces += (shownAdvPlaces == '' ? ';' : '')+idPlace+';'; // Old scheme - inline method }else{ if (!document.usedAdvData) document.usedAdvData = ''; rndseed = new String(Math.random()); rndseed = rndseed.substring(2,11); document.write ("<" + "script language='JavaScript' type='text/javascript' src='"+viewURL+"aproc.php?action=view&rs="+advCurTmStamp.getTime()+rndseed+"&place="+idPlace+"&used="+document.usedAdvData+"&curl="+encodeURIComponent(viewURL)+"&referer="+encodeURIComponent(advReferrer)+"'><"+"/script>"); } } function showAdvBanner(id, content){ if(document.usedAdvData) document.usedAdvData += ','+id+','; else document.usedAdvData = ','+id+','; document.writeln(content); } function aLnkClick(lnkID){ var aLink = frontBaseHref+"aproc.php?action=lclick&id="+lnkID+"&page_url="+encodeURIComponent(document.location.href); advClick(aLink); } function advClick(clickURL){ rndseed = new String(Math.random()); rndseed = rndseed.substring(2,11); clickURL+="&rs="+advCurTmStamp.getTime()+rndseed; img = new Image(); img.src = clickURL; } var advPlacesContent = new Array(); var fillAdvPlaceWatcher = new Array(); function fillAdvPlace(idPlace, idCnt, placeContent){ if(advPlacesContent[idPlace+'_'+idCnt] == undefined) advPlacesContent[idPlace+'_'+idCnt] = placeContent; if(fillAdvPlaceWatcher[idPlace+'_'+idCnt] == undefined) fillAdvPlaceWatcher[idPlace+'_'+idCnt] = 0; if(document.getElementById && document.getElementById('advp_'+idPlace+'_'+idCnt) && document.getElementById('advp_'+idPlace+'_'+idCnt).innerHTML != undefined){ document.getElementById('advp_'+idPlace+'_'+idCnt).innerHTML = advPlacesContent[idPlace+'_'+idCnt]; }else{ fillAdvPlaceWatcher ++; if(fillAdvPlaceWatcher < 1000) setTimeout("fillAdvPlace('"+idPlace+"', '"+idCnt+"');", 100); } } /* MODULE ADVERTISEMENT PART [not in use] */ /* // String that contains module show data var modAdvIdsArr = new Array(); // Set item view function setView(modName, bodyType, id, idPlace){ if(isNaN(idPlace)) idPlace = 0; var isFound = 0; for(var i = 0; i < modAdvIdsArr.length; i++){ if(modAdvIdsArr[i][0] == modName){ modAdvIdsArr[i][1] += '|'+bodyType+id+','+idPlace; isFound = 1; break; } } if(!isFound) modAdvIdsArr[modAdvIdsArr.length] = new Array(modName, bodyType+id+','+idPlace); } // Process gathered adv IDs function processViewAdvIds(){ var retStr = ''; for(var i = 0; i < modAdvIdsArr.length; i++) retStr += (retStr != '' ? ';' : '')+modAdvIdsArr[i][0]+'='+modAdvIdsArr[i][1]; alert(retStr); return retStr; } */ // Returns cookie value function getPlainCookie(name){ // cookies are separated by semicolons var aCookie = document.cookie.split("; "); var value = ""; for (var i=0; i < aCookie.length; i++){ // a name/value pair (a crumb) is separated by an equal sign var aCrumb = aCookie[i].split("="); if (name == aCrumb[0]){ if(aCrumb[1] === undefined) { value = null; }else{ value = aCrumb[1]; } return value; } } // a cookie with the requested name does not exist return null; } function getCookie(name, useDecodeURIComponent){ var val = getPlainCookie(name); if(val != null){ if(useDecodeURIComponent){ val = decodeURIComponent(val); val = val.replace(/\+/g, ' '); }else{ val = decodeURIComponent(val); } } return val; } /* function updateCookieExpireTime(name, minutes){ var oDate = new Date(); if (typeof(minutes) != "undefined") oDate.setMinutes(oDate.getMinutes() + minutes); var val = getCookie(name); if(val != null){ _setCookie(name, val, "/", oDate); } } */ // {{{ window.onLoad events queue implementation var onLoadEvents = new Array (); var previousOnLoadEvent; function addOnLoadEvent(event) { onLoadEvents[onLoadEvents.length] = event; } function runOnLoadEventsQueue() { if (previousOnLoadEvent) { previousOnLoadEvent(); } for (var i = 0 ; i < onLoadEvents.length; i++) { onLoadEvents[i](); } } function savePreviousOnLoadEvent() { previousOnLoadEvent = window.onload; window.onload = runOnLoadEventsQueue; } // }}} function setCaptchaMD5Hash(sid) { var cookie = getCookie('captcha_' + sid); if (cookie != null && cookie.length) { clearInterval(eval("intervalId_" + sid)); eval("captcha_" + sid + " = cookie;"); var path = null; var domain = null; if (location) { domain = location.host; path = frontBaseHref.replace(/^\w+\:\/\/[^\/]+/, ''); } delCookie('captcha_' + sid, path, domain); } } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(val, fromIndex) { if (typeof(fromIndex) != 'number') { fromIndex = 0; } for (var index = fromIndex,len = this.length; index < len; index++) { if (this[index] == val) { return index; } } return -1; } } if (!Array.prototype.splice) { Array.prototype._splice = function(start) { if (start >= this.length) { return; } return this.slice(start); } Array.prototype._splice = function(start, deleteCount) { if (start >= this.length) { return; } return this.slice(0, start-1).concat(this.slice(start + deleteCount)); } } function cloneArray(source) { var destination = new Array(); for (var i = 0 ; i < source.length ; i++) { if (!(typeof(source[i]) == 'undefined')) { destination[i] = source[i]; } } return destination; } /* products comparison */ var mComparisonList = new Array (), mComparisonURL = ''; function compare(key) { if (compareProducts.indexOf(key) >= 0) { alert(compareInComparisonAlready); return false; } if (mComparisonList.length && !confirm(compareAddSelected)) { return false; } if (compareProducts.length == compareMaxQuantity) { alert(compareMaxMessage); return false; } if (mComparisonList.indexOf(key) < 0) { mComparisonList.push(key); } // check for different datasets if (compareDisallowDifferentDatasets && compareProducts.length > 0) { var datasetId = compareDatasetId; var _mComparisonList = cloneArray(mComparisonList); for (var i = 0, qty = _mComparisonList.length ; i < qty ; i++) { var p = _mComparisonList[i].split('-'); // p[2] is containing datasetId now if (!compareDatasetId) { compareDatasetId = p[2]; } if (compareDatasetId != p[2]) { if (!confirm(compareConfirmOtherDataset)) { return false; } break; } } } return mSubmitAddToCompare(); } function compareClear() { if (confirm(compareConfirmListClearing)) { document.location = location.pathname + '?action=compareClear'; } return false; } function mCompare(oCheckbox) { var key = oCheckbox.value; if (oCheckbox.checked) { // exclude duplicates if (compareProducts.indexOf(key) >= 0) { alert(compareInComparisonAlready); oCheckbox.checked = false; return false; } // check for max quantity of products to compare if (compareProducts.length == compareMaxQuantity) { alert(compareMaxMessage); oCheckbox.checked = false; return false; } // check for different datasets if (compareDisallowDifferentDatasets) { var p = key.split('-'); if ((compareProducts.length + mComparisonList.length) > 0 && p[2] != copmpareLastDatasetId && !confirm(compareConfirmOtherDataset)) { oCheckbox.checked = false; return false; } copmpareLastDatasetId = p[2]; // uncheck checked products having other dataset var _mComparisonList = cloneArray(mComparisonList); for (var i = 0, qty = _mComparisonList.length ; i < qty ; i++) { var p = _mComparisonList[i].split('-'); if (p[2] != copmpareLastDatasetId) { var o = document.getElementById('cmp_' + _mComparisonList[i]); o.checked = false; mCompare(o); } } // count real number of products to comapere after adding var _compareProducts = cloneArray(compareProducts); for (var i = 0, qty = compareProducts.length ; i < qty ; i++) { var p = compareProducts[i].split('-'); if (p[2] != copmpareLastDatasetId) { var index = _compareProducts.indexOf(compareProducts[i]); if (Array.prototype.splice) { _compareProducts.splice(index, 1); } else { _compareProducts = mComparisonList._splice(index, 1); } } } // check for max quantity of products to compare after manipulations if (_compareProducts.length + mComparisonList.length >= compareMaxQuantity) { alert(compareMaxMessage); oCheckbox.checked = false; return false; } } mComparisonList.push(key); } else { var index = mComparisonList.indexOf(key); if (index > -1) { if (Array.prototype.splice) { mComparisonList.splice(index, 1); } else { mComparisonList = mComparisonList._splice(index, 1); } copmpareLastDatasetId = compareDatasetId; } } } function mSubmitAddToCompare() { var qty = mComparisonList.length; if (!qty) { alert(compareListIsEmpty); return false; } var _mComparisonList = cloneArray(mComparisonList); // check for added already products and exclude its from mComparisonList for (var i = 0 ; i < qty ; i++) { var index = compareProducts.indexOf(_mComparisonList[i]); if (index >= 0) { // exclude duplicate product if (Array.prototype.splice) { mComparisonList.splice(_mComparisonList.indexOf(mComparisonList[i]), 1); } else { mComparisonList = mComparisonList._splice(_mComparisonList.indexOf(mComparisonList[i]), 1); } } } document.location = location.pathname + '?action=compare&products=' + _mComparisonList.join(';'); return false; } function mCompareSelected(url) { if (mComparisonList.length < 2) { if (mComparisonList.length < 1 && compareProducts.length > 1) { window.open(frontBaseHref + url + '?p=' + compareProducts.join(';') + '&h=&v=all&lay_id=100'); return false; } alert(compareListInsufficient); return false; } if (compareProducts.length && !confirm(compareConfirmPreviousClearing)) { return false; } window.open(frontBaseHref + url + '?p=' + mComparisonList.join(';') + '&h=&v=all&lay_id=100'); return false; } /* /products comparison */ function getXPos(elem){ x = 0; do { x += elem.offsetLeft; } while((elem = elem.offsetParent) != null); return x; } function getYPos(elem){ y = 0; do { y += elem.offsetTop; } while((elem = elem.offsetParent) != null); return y; } var calendarBlock; var calendarDateFieldName; function getCalendar(in_dateField, lang, dateFormat, divIdPrefix){ var elevPrefix = typeof(divIdPrefix) == 'undefined' ? '' : divIdPrefix; calendarTarget = in_dateField; calendarBlock = document.getElementById(elevPrefix + "calendar_block"); if(calendarBlock && (calendarBlock.style.display!="block" || (in_dateField.form.name + in_dateField.name!=calendarDateFieldName))){ calendarDateFieldName = in_dateField.form.name + in_dateField.name; cLeft = getXPos(calendarTarget)+calendarTarget.offsetWidth; cTop = getYPos(calendarTarget)+calendarTarget.offsetHeight; var dconfAddon = ''; if(typeof(dateFormat) != 'undefined' && dateFormat != ''){ dconfAddon = '&date_format='+dateFormat; } document.getElementById(elevPrefix + "calendar_block_frm").src = "calendar.php?v=2&lang="+lang+dconfAddon; calendarBlock.style.display="block"; var correctLeft = cLeft + calendarBlock.offsetWidth - document.body.scrollLeft - document.body.clientWidth; var correctTop = cTop + calendarBlock.offsetHeight - document.body.scrollTop - document.body.clientHeight; calendarBlock.style.left = cLeft - ((correctLeft > 0)?correctLeft:0) + 'px'; calendarBlock.style.top = cTop - ((correctTop > 0)?correctTop:0) + 'px'; document.getElementById(elevPrefix + "calendar_block_frm").contentWindow.document.body.focus(); }else if(calendarBlock){ calendarBlock.style.display="none"; } } function replaceDateTitle(objId){ var objObj = document.getElementById(objId); if(objObj){ var curDate = objObj.innerHTML; var rxToday = new RegExp(DATE_CONVERTION[2].replace(/\./g, "\\.")); var rxYesterday = new RegExp(DATE_CONVERTION[3].replace(/\./g, "\\.")); curDate = curDate.replace(rxToday, DATE_CONVERTION[0]); curDate = curDate.replace(rxYesterday, DATE_CONVERTION[1]); objObj.innerHTML = curDate; } } /* Пример использования календаря
дата:
*/ function saveURLHistory(){ var uh_prev_mod = getCookie('uh_prev_mod'); var uh_prev_url = getCookie('uh_prev_url'); var uh_curr_mod = getCookie('uh_curr_mod'); var uh_curr_url = getCookie('uh_curr_url'); delCookie('uh_prev_mod', "/"); delCookie('uh_prev_url', "/"); delCookie('uh_curr_mod', "/"); delCookie('uh_curr_url', "/"); if(uh_curr_mod == null){ setCookie('uh_prev_mod', active_module, "/"); setCookie('uh_prev_url', active_module_link, "/"); setCookie('uh_curr_mod', active_module, "/"); setCookie('uh_curr_url', active_module_link, "/"); }else if(uh_curr_mod != active_module){ setCookie('uh_prev_mod', uh_curr_mod, "/"); setCookie('uh_prev_url', uh_curr_url, "/"); setCookie('uh_curr_mod', active_module, "/"); setCookie('uh_curr_url', active_module_link, "/"); }else{ setCookie('uh_prev_mod', uh_prev_mod, "/"); setCookie('uh_prev_url', uh_prev_url, "/"); setCookie('uh_curr_mod', active_module, "/"); setCookie('uh_curr_url', active_module_link, "/"); } } saveURLHistory(); function amiFrontCommonClass(){ this.serialize = function(oData){ var result = ''; if(typeof(oData) == "object"){ if(oData instanceof Array){ result += 'a'; for(var i = 0; i < oData.length; i++){ var item = oData[i].toString(); result += item.length.toString() + '.' + item; } }else{ result += 'o'; for(var oKey in oData){ result += oKey.length.toString() + '.' + oKey + oData[oKey].length.toString() + '.' + oData[oKey]; } } } return result; } this.unserialize = function(oString){ var oData = null; if(oString.charAt(0) == 'a' || oString.charAt(0) == 'o'){ var isArray = oString.charAt(0) == 'a'; if(isArray){ oData = new Array(); }else{ oData = new Object(); } var dataLength = ''; var isShouldBeKey = isArray ? false : true; var keyValue = ''; for(var i = 1; i < oString.length; i++){ if(oString.charAt(i).match(/\d/)){ dataLength += oString.charAt(i); }else if(oString.charAt(i) == '.'){ dataLength = parseInt(dataLength); if(isShouldBeKey){ keyValue = oString.substr(i + 1, dataLength); isShouldBeKey = false; }else{ if(isArray){ oData[oData.length] = decodeURIComponent(oString.substr(i + 1, dataLength)); }else{ oData[keyValue] = decodeURIComponent(oString.substr(i + 1, dataLength)); isShouldBeKey = true; } keyValue = ''; } i = i + dataLength; dataLength = ''; } } } return oData; } } var amiFrontCommon = new amiFrontCommonClass(); function amiSessionClass(cookieName, sessionCookieName, cookieDays, cookieHours){ this.sessionCookieName = sessionCookieName; this.cookieName = cookieName; this.cookieDays = cookieDays; this.cookieHours = cookieHours; this.variables = new Object(); this.init = function(){ this.loadVariables(); } this.setCookieName = function(value){ this.cookieName = value; } this.setCookieLifetime = function(iDays, iHours){ this.cookieDays = iDays; this.cookieHours = iHours; } this.set = function(name, value){ this.variables[name] = value; this.storeVariables(); } this.del = function(name){ delete this.variables[name]; this.storeVariables(); } this.get = function(name){ if(typeof(this.variables[name]) != 'undefined'){ return this.variables[name]; } return ''; } this.storeVariables = function(){ var sVariables = amiFrontCommon.serialize(this.variables); setCookie(this.cookieName, sVariables, '/', this.cookieDays, this.cookieHours, true); } this.loadVariables = function(){ var sessionCookie = getCookie(this.sessionCookieName); if(sessionCookie != null){ var sVariables = getCookie(this.cookieName, true); this.variables = new Object(); if(sVariables != null){ this.variables = amiFrontCommon.unserialize(sVariables); if(typeof(this.variables) != 'object'){ this.variables = new Object(); } } }else{ delCookie(this.cookieName); } } this.init(); } var amiSession = new amiSessionClass('user_session', sessionCookieName, 30, 0); //updateCookieExpireTime('user_session', sessionTimeout); function amiGetUsername(source){ var res; if(source == 'username'){ res = amiSession.get('username_cookie'); }else{ res = amiSession.get('firstname_cookie') + ' ' + amiSession.get('lastname_cookie'); res = res.replace(/^\s*/, '').replace(/\s*$/, ''); } return res; } var flagNames = new Array(); var flagMaps = new Array(); function _dec_to_rgb(value) { var hex_string = ""; for (var hexpair = 0; hexpair < 3; hexpair++) { var onebyte = value & 0xFF; // get low onebyte value >>= 8; // drop low onebyte var nybble2 = onebyte & 0x0F; // get low nybble (4 bits) var nybble1 = (onebyte >> 4) & 0x0F; // get high nybble hex_string += nybble1.toString(16); // convert nybble to hex hex_string += nybble2.toString(16); // convert nybble to hex } return hex_string.toUpperCase(); } function flagMapAdd(name, num, isCr){ if(!isNaN(num)){ mapID = -1; for(i = 0; i < flagNames.length; i++){ if(flagNames[i] == name){ mapID = i; break; } } if(mapID == -1){ mapID = flagNames.length; flagNames[mapID] = name; flagMaps[mapID] = new Array(); } if(flagMaps[mapID].length < num){ for(i = 0; i < num; i++) if(!flagMaps[mapID][i]) flagMaps[mapID][i] = 0; } if(!isCr) flagMaps[mapID][num-1] = 1; } } function arrToHex(arrIn){ realValTmp = ""; realVal = ""; var tmp = ""; var isLastProcessed = true; for(k = 1; k <= arrIn.length; k++){ isLastProcessed = false; tmp = arrIn[k-1]+tmp; if(k % 4 == 0){ realValTmp += parseInt(tmp, 2).toString(16); tmp = ""; isLastProcessed = true; } } if(!isLastProcessed) realValTmp += parseInt(tmp, 2).toString(16); hexZeroStart = true; for(k = realValTmp.length-1; k >= 0; k--){ if(realValTmp.substr(k, 1) != "0" || !hexZeroStart){ realVal += realValTmp.substr(k, 1); hexZeroStart = false; } } return realVal; } function CheckFilterForms(fform, isSearchForm, isOrder, skipOffestSetting) { var forceSubmitUrl; var _tmpVarName; _tmpVarName = fform.name + "_forceSubmitUrl"; forceSubmitUrl = eval("if(typeof("+_tmpVarName+") != 'undefined') {"+_tmpVarName+"} else {''}"); if(isOrder != 1) isOrder = 0; // special run over checkbox filter fields //if() for(var i=0; i= 0 && isOrder){ if((fpos = el.name.lastIndexOf("_x")) >= 0){ elName = el.name.substr(0, fpos); } elName += "[]"; } if(el.type == 'checkbox'){ if(el.checked){ if((fpos = el.name.indexOf("_flag_")) >= 0){ flagMapAdd(el.name.substr(0, fpos), parseInt(el.name.substr(fpos+6)), 0); }else if(el.value != ''){ submitURL += '&'+elName+'='+encodeURIComponent(el.value); } }else{ if((fpos = el.name.indexOf("_flag_")) >= 0){ flagMapAdd(el.name.substr(0, fpos), parseInt(el.name.substr(fpos+6)), 1); }else{ //if(el.name.indexOf("[]") <= 0) /* do not process array items */ // submitURL += '&'+elName+'='; } } }else if(el.type == 'select-one'){ if((fpos = el.name.indexOf("_flag")) >= 0){ flagMapAdd(el.name.substr(0, fpos), parseInt(el.value), 0); }else if(el.value != ''){ submitURL += '&'+elName+'='+encodeURIComponent(el.value); } }else if(el.type == 'select-multiple'){ fpos = el.name.indexOf("_flag"); for(k = 0; k < el.length; k++){ if(el.options[k].selected){ if(fpos >= 0){ flagMapAdd(el.name.substr(0, fpos), parseInt(el.options[k].value), 0); }else{ submitURL += '&'+encodeURIComponent(elName)+'='+encodeURIComponent(el.options[k].value); } } } }else if(el.type == 'radio'){ if(el.checked){ if((fpos = el.name.indexOf("_flag")) >= 0){ flagMapAdd(el.name.substr(0, fpos), parseInt(el.value), 0); }else{ submitURL += '&'+elName+'='+encodeURIComponent(el.value); } } }else{ if(el.name == "action" && ((!isOrder && fform.search_subcats && fform.search_subcats.checked) || isSearchForm)) { submitURL += '&action=search'; } else if(el.value != '' && elName != 'btnFlt_apply' && (!isOrder || el.name != "action" && el.name != "order")) { submitURL += '&'+elName+'='+encodeURIComponent(el.value); } } } for(i = 0; i < flagMaps.length; i++){ if(flagNames[i]){ submitURL += '&'+flagNames[i]+'=0x'+arrToHex(flagMaps[i]); } } if(isOrder) submitURL += 'eshop_special=1&action=add'; document.location.href=submitURL; return false; } function checkSearchForms(fform, fltFormName) { if(typeof(fltFormName) != 'undefined') { _cms_document_form = fltFormName; } else if(typeof(_cms_document_form) == 'undefined') { _cms_document_form = _cms_filter_form; } var sform = document.forms[_cms_document_form]; // special run over checkbox filter fields for(var i=0; i= 0 || navigator.appVersion.indexOf('iPhone;') >= 0 || navigator.appVersion.indexOf('iPod;') >= 0, getWindowWidth : function(){ return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth; }, getWindowHeight : function(){ return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight; }, getDocumentWidth : function(){ return Math.max(this.getWindowWidth(), document.body.scrollWidth || document.documentElement.scrollWidth); }, getDocumentHeight : function(){ return Math.max(this.getWindowHeight(), document.body.scrollHeight || document.documentElement.scrollHeight); }, getDocumentLeft : function(){ return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft); }, getDocumentTop : function(){ return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop); }, getPointerPosition : function(oEvent){ var aData = new Array(0, 0); oEvent = oEvents.validate(oEvent); if(oEvent.pageX || oEvent.pageY){ aData[0] = oEvent.pageX; aData[1] = oEvent.pageY; }else if(oEvent.clientX || oEvent.clientY){ aData[0] = oEvent.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft; aData[1] = oEvent.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop; } return aData; }, getObjectPosition : function(oObject, bStopOnRelative){ if(typeof(bStopOnRelative) == 'undefined'){ bStopOnRelative = false; } var aData = new Array(0, 0); do{ if(bStopOnRelative){ var positionStyle = AMI.Browser.DOM.getStyle(oObject, 'position'); if(positionStyle == 'relative' || positionStyle == 'absolute' || positionStyle == 'fixed'){ break; } } aData[0] += oObject.offsetLeft; aData[1] += oObject.offsetTop; }while((oObject = oObject.offsetParent) != null); return aData; }, getCaretPosition : function(textObject){ var result = 0; textObject.focus(); if(textObject.selectionStart){ result = textObject.selectionStart; }else if(document.selection){ var rangeSelect = document.selection.createRange(); rangeSelect.collapse(true); var rangeObject = textObject.createTextRange(); if(rangeObject.inRange(rangeSelect)){ rangeObject.setEndPoint('EndToEnd', rangeSelect); result = rangeObject.text.length } } return result; }, setCaretPosition : function(textObject, position){ textObject.focus(); if(textObject.selectionStart){ textObject.selectionStart = position; textObject.selectionEnd = position; }else if(document.selection){ var rangeObject = textObject.createTextRange(); rangeObject.move('character', position); rangeObject.select(); } }, setOpacity: function(oElement, iOpacity){ if(typeof(oElement.style.MozOpacity) != "undefined"){ oElement.style.MozOpacity = iOpacity; }else if(typeof(oElement.style.opacity) != "undefined"){ oElement.style.opacity = iOpacity; }else if(typeof(oElement.style.KhtmlOpacity) != "undefined"){ oElement.style.KhtmlOpacity = iOpacity; }else{ oElement.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + (iOpacity * 100) + ");"; } } } AMI.Browser.Cookie = { set : function(sName, sValue, iHours){ var oDate = new Date(); if(typeof(iHours) == "undefined"){ iHours = 1; } oDate.setHours(oDate.getHours() + iHours); this.del(sName); document.cookie = sName + "=" + escape(sValue) + "; path=/; expires="+oDate.toGMTString(); }, del : function(sName) { if(this.get(sName)){ document.cookie = sName + "=" + "; path=/ ;expires=Thu, 01-Jan-1970 00:00:01 GMT"; } }, get : function(sName){ var aCookie = document.cookie.split("; "); var value = ""; for(var i = 0; i < aCookie.length; i++){ var aCrumb = aCookie[i].split("="); if(sName == aCrumb[0]){ if(typeof(aCrumb[1]) == 'undefined'){ value = null; }else{ value = unescape(aCrumb[1]); } return value; } } return null; } } AMI.Browser.Event = { validate: function(oEvent){ return oEvent ? oEvent : window.event; }, getTarget: function(oEvent){ oEvent = this.validate(oEvent); return oEvent.srcElement || oEvent.target; }, fire: function(oTarget, sEvent){ if(document.createEventObject){ var oEvent = document.createEventObject(); oTarget.fireEvent('on' + sEvent, oEvent); }else if(document.createEvent){ var oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent(sEvent, true, true); oTarget.dispatchEvent(oEvent); }else{ return false; } return true; }, addHandler: function(oTarget, sEvent, oHandler){ if(typeof(oTarget.addEventListener) != 'undefined'){ oTarget.addEventListener(sEvent, oHandler, false); }else{ oTarget.attachEvent('on' + sEvent, oHandler); } }, removeHandler: function(oTarget, sEvent, oHandler){ if(typeof(oTarget.removeEventListener) != 'undefined'){ oTarget.removeEventListener(sEvent, oHandler, false); }else if(oTarget.detachEvent){ oTarget.detachEvent('on' + sEvent, oHandler); } }, stopProcessing: function(oEvent){ oEvent = this.validate(oEvent); if(typeof(oEvent.stopPropagation) != 'undefined'){ oEvent.stopPropagation(); }else if(typeof(oEvent.cancelBubble) != 'undefined'){ oEvent.cancelBubble = true; } if(typeof(oEvent.preventDefault) != 'undefined'){ oEvent.preventDefault(); }else{ oEvent.returnValue = false; } } } AMI.Browser.DOM = { create: function(sTagName, sId, sClassName, sStyles, oParentNode){ var oObject = document.createElement(sTagName); if(typeof(sId) != 'undefined' && sId != ''){ oObject.id = sId; } if(typeof(sClassName) != 'undefined' && sClassName != ''){ oObject.className = sClassName; } if(typeof(sStyles) != 'undefined' && sStyles != ''){ oObject.style.cssText = sStyles; } return oParentNode == null ? oObject : this.append(oParentNode, oObject); }, append: function(oParentNode, oNode){ return oParentNode.appendChild(oNode); }, getStyle: function(oObject, sStyleName){ var sResult = ''; if(window.getComputedStyle){ var oDeclaration = window.getComputedStyle(oObject, sStyleName); sResult = oDeclaration.getPropertyValue(sStyleName); }else if(oObject.currentStyle){ var i; while((i = sStyleName.indexOf("-")) != -1){ sStyleName = sStyleName.substr(0, i) + sStyleName.substr(i+1,1).toUpperCase() + sStyleName.substr(i+2); } if(oObject.currentStyle[sStyleName]){ sResult = oObject.currentStyle[sStyleName]; } } return sResult; } } AMI.Message = { oListeners: {}, addListener: function(sMessage, oCallback){ if(typeof(this.oListeners[sMessage]) == 'undefined'){ this.oListeners[sMessage] = []; } this.oListeners[sMessage].push(oCallback); }, removeListener: function(sMessage, oCallback){ if(typeof(sMessage) == 'undefined'){ this.oListeners = {}; }else if(typeof(oCallback) == 'undefined'){ if(typeof(this.oListeners[sMessage]) != 'undefined'){ this.oListeners[sMessage] = []; } }else{ if(typeof(this.oListeners[sMessage]) != 'undefined'){ var iListenersNumber = this.oListeners[sMessage].length; for(var i = 0; i < iListenersNumber; i++){ if(this.oListeners[sMessage][i] == oCallback){ this.oListeners[sMessage][i] = null; } } } } }, send: function(sMessage, param1, param2){ if(typeof(this.oListeners[sMessage]) != 'undefined'){ param1 = typeof(param1) == 'undefined' ? null : param1; param2 = typeof(param2) == 'undefined' ? null : param2; var iListenersNumber = this.oListeners[sMessage].length; for(var i = 0; i < iListenersNumber; i++){ if(this.oListeners[sMessage][i] != null){ if(!this.oListeners[sMessage][i](param1, param2)){ break; } } } } } } AMI.Template = { currentValues : null, conditionStrings : new Array(), storeConditionStrings : function(match, quote, str, offset, originalString){ var result = this.conditionStrings.length; this.conditionStrings[result] = quote + str + quote; return '"' + result + '"'; }, restoreConditionStrings : function(match, position, offset, originalString){ if(typeof(this.conditionStrings[position]) != 'undefined'){ return this.conditionStrings[position]; }else{ return ''; } }, getCondition : function(construction){ construction = construction.replace(/\\'/g, "'").replace(/\\\\/g, '\\').replace(/&/g, '&'); this.conditionStrings = new Array(); construction = construction.replace( /('|")((?:.|[\r\n])*?)\1/g, function(_this){ return function(match, quote, str, offset, originalString){ return _this.storeConditionStrings(match, quote, str, offset, originalString); } }(this) ); construction = construction.replace(/(^|[^"\'A-Za-z\_0-9\[])([0-9A-Za-z\_]*[A-Za-z_]+[0-9A-Za-z\_]*)([^\]"\'A-Za-z\_0-9\(\[]|$)/g, '$1AMI.Template.getValue("$2")$3'); construction = construction.replace( /"(\d+)"/g, function(_this){ return function(match, position, offset, originalString){ return _this.restoreConditionStrings(match, position, offset, originalString); } }(this) ); return construction; }, replaceSpecial : function(match, construction, offset, originalString){ var result = ''; if(matches = construction.match(/^if\((.*?)\)$/)){ result = "'; if(" + this.getCondition(matches[1]) + "){evalResult += '"; }else if(matches = construction.match(/^else if\((.*?)\)$/)){ result = "';} else if(" + this.getCondition(matches[1]) + "){evalResult += '"; }else if(construction == 'else'){ result = "';} else { evalResult += '"; }else if(construction == 'endif'){ result = "';} evalResult += '"; }else if(/^[a-zA-Z0-9_\.\-]+$/.test(construction)){ result = "' + AMI.Template.getValue('" + construction + "') + '"; }else{ result = match; } return result; }, getValue : function(varKey){ if(typeof(this.currentValues[varKey]) != 'undefined'){ return this.currentValues[varKey]; }else{ return ''; } }, parse : function(content, aData){ content = "'" + content.replace(/\\/g, '\\' + '\\').replace(/'/g, "\\'").replace(/\r/g, '').replace(/\n/g, "\\" + "\n") + "';"; content = content.replace( /@@(.*?)@@/g, function(_this){ return function(match, construction, offset, originalString){ return _this.replaceSpecial(match, construction, offset, originalString); } }(this) ); this.currentValues = aData; var evalResult = ''; eval('evalResult = ' + content); return evalResult; } } AMI.String = { decodeHTMLSpecialChars : function(content){ return content.replace(/&(.{2,4});/gi, function(wholeString, match){ // Remember to change php unhtmlentities when expanding replacements var associations = { '#039' : "'", '#037' : "%", '#035' : '#', 'quot' : '"', 'lt' : '<', 'gt' : '>', 'amp' : '&' }; if(associations[match]){ return associations[match]; }else{ return match; } }); }, decodeJSON: function(data){ var oResult; eval('oResult = ' + data); return oResult; } } AMI.HTTPRequest = { requests: new Array(), variables: {}, urlHash: '', // Init XML HTTP object _initObjectRequest: function(requestId){ try{ this.requests[requestId]['transport'] = new XMLHttpRequest(); }catch(exception){ this.requests[requestId]['transport'] = null; } if(this.requests[requestId]['transport'] == null){ for(var i = 0; i < 2; i++){ activeXName = i == 0 ? 'Msxml2.XMLHTTP' : 'Microsoft.XMLHTTP'; try{ this.requests[requestId]['transport'] = new ActiveXObject(activeXName); }catch(exception){ this.requests[requestId]['transport'] = null; } if(this.requests[requestId]['transport'] != null){ break; } } } return (this.requests[requestId]['transport'] != null); }, // Create query string from variables object _getRequestVariables: function(requestId){ var variables = ''; for(var key in this.requests[requestId]['variables']){ variables += variables.length > 0 ? '&' : ''; variables += encodeURIComponent(key) + '=' + encodeURIComponent(this.requests[requestId]['variables'][key]); } return variables; }, // Create valid url for request _prepeareUrl: function(requestId){ var url = this.requests[requestId]['url']; if(this.requests[requestId]['method'] == 'GET'){ var variables = this._getRequestVariables(requestId); if(variables.length > 0){ url = url + '?' + variables; } if(this.requests[requestId]['hash'].length > 0){ url = url + '#' + encodeURIComponent(this.requests[requestId]['hash']); } }else if(this.requests[requestId]['method'] == 'POST'){ // ?? Required to check this part of code var variables = this._getRequestVariables(requestId); this.requests[requestId]['transport'].send(variables); } return url; }, // Process request for session parameters _request: function(requestId){ if(this._initObjectRequest(requestId)){ this.requests[requestId]['transport'].open(this.requests[requestId]['method'], this._prepeareUrl(requestId), true); if(this.requests[requestId]['method'] == 'GET'){ this.requests[requestId]['transport'].setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT'); this.requests[requestId]['transport'].send(null); }else{ this.requests[requestId]['transport'].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); this.requests[requestId]['transport'].send(this._getRequestVariables(requestId)); } setTimeout('AMI.HTTPRequest._checkResponse('+requestId+')', 10); }else{ alert('Problem with XML HTTP initialization'); } }, // Check the response from server and process action _checkResponse: function(requestId){ if(this.requests[requestId]['transport'].readyState == 4){ if(this.requests[requestId]['transport'].status == 200){ this.requests[requestId]['status'] = 1; this.requests[requestId]['content'] = this.requests[requestId]['transport'].responseText; }else{ this.requests[requestId]['status'] = 2; } if(this.requests[requestId]['callback'] != null){ this.requests[requestId]['callback'](this.requests[requestId]['status'], this.requests[requestId]['content']); } this.requests[requestId]['transport'] = null; this.requests[requestId] = null; }else{ setTimeout('AMI.HTTPRequest._checkResponse('+requestId+')', 10); } }, // Remove all query variables resetRequestVariables: function(){ this.variables = {}; }, // Add query variable addVariable: function(key, value){ this.variables[decodeURIComponent(key)] = decodeURIComponent(value); }, // Set url hash code setUrlHash: function(value){ this.urlHash = decodeURIComponent(value); }, // Parse query string and create variables object addVariablesFromString: function(variables){ this.resetRequestVariables(); variables = variables.replace(/^[\s?]*(.*?)[\s]*$/g, '$1'); var aHash = variables.split('#'); if(typeof(aHash[1]) != 'undefined'){ variables = aHash[0]; this.setUrlHash(aHash[1]); }else{ this.setUrlHash(''); } var aPairs = variables.split('&'); for(var i = 0; i < aPairs.length; i++){ aPair = aPairs[i].split('='); if(aPair[0] != ''){ this.addVariable(aPair[0], aPair[1]); } } }, getContent: function(method, url, variables, callbackFunction){ var requestId = this.requests.length; this.requests[requestId] = {}; this.requests[requestId]['status'] = 0; this.requests[requestId]['callback'] = typeof(callbackFunction) == 'function' ? callbackFunction : null; this.requests[requestId]['transport'] = null; this.requests[requestId]['method'] = method.toUpperCase(); this.requests[requestId]['url'] = url; if(typeof(variables) != 'undefined'){ this.addVariablesFromString(variables); } this.requests[requestId]['variables'] = this.variables; this.requests[requestId]['hash'] = this.urlHash; this.requests[requestId]['content'] = ''; this._request(requestId); }, submitForm: function(url, callbackFunction){ this.getContent('POST', url, '', callbackFunction); } } AMI.UI = {} AMI.UI.List = function(containerId, requestData){ this.idContainer = containerId; this.oProgress = null; this.oContainer = null; this.oPrevious = null; this.oNext = null; this.oPlayPause = null; this.oDebug = null; this.sRowTemplateId = 'itemRowTemplate_' + containerId; this.aRequestData = requestData; // Refresh data this.refreshInterval = typeof(requestData.refreshInterval) == 'undefined' ? 0 : Math.max(1, parseFloat(requestData.refreshInterval)); this.refreshIntervalInitial = this.refreshInterval; this.refreshMultiplier = typeof(requestData.refreshIntervalMultiplier) == 'undefined' ? 0 : Math.max(1, parseFloat(requestData.refreshIntervalMultiplier)); this.refreshMaximum = typeof(requestData.refreshNumber) == 'undefined' ? 50 : Math.min(50, parseInt(requestData.refreshNumber)); this.refreshMaximumInitial = this.refreshMaximum; this.refreshType = typeof(requestData.refreshType) == 'undefined' ? 'reload' : requestData.refreshType; this.refreshTimeout = null; this.refreshPaused = false; this.lastAction = ''; this.lastRecordsCount = 0; this.scriptName = 'ami_resp'; this.scriptExt = 'php'; this.init = function(){ this.oContainer = document.getElementById('amiContent' + containerId); this.oProgress = document.getElementById('amiProgress' + containerId); this.oPrevious = document.getElementById('amiNavPreviuos' + containerId); this.oNext = document.getElementById('amiNavNext' + containerId); this.oPlayPause = document.getElementById('amiNavPlayPause' + containerId); if(this.oProgress == null && this.oContainer != null){ this.oProgress = AMI.Browser.DOM.create('DIV', '', 'amiListProgress', '', this.oContainer.parentNode); var oProgressImage = AMI.Browser.DOM.create('IMG', '', '', '', this.oProgress); oProgressImage.src = '/_img/ami_jsapi/loader.gif'; } if(isNaN(this.refreshMaximum)){ this.refreshMaximum = 0; this.refreshMaximumInitial = 0; } if(this.refreshInterval > 0 && this.refreshMaximum > 0){ this.oPlayPause.className = this.oPlayPause.className.replace(/\s*ami_resp_play_pause_disabled/, ''); } AMI.Message.send('ON_AMI_LIST_READY', this.idContainer, this); } this.showProgress = function(){ if(this.oProgress != null){ var oPos = AMI.Browser.getObjectPosition(this.oContainer, true); this.oProgress.style.left = oPos[0] + 'px'; this.oProgress.style.top = oPos[1] + 'px'; this.oProgress.style.width = this.oContainer.offsetWidth + 'px'; this.oProgress.style.height = this.oContainer.offsetHeight + 'px'; this.oProgress.style.display = 'block'; } } this.hideProgress = function(){ if(this.oProgress != null){ this.oProgress.style.display = 'none'; } } this.updatePrevNext = function(iDisableNext){ if(this.oPrevious != null){ if(parseInt(this.aRequestData.offset) <= 0 && this.oPrevious.className.indexOf('ami_resp_prev_disabled') == -1){ AMI.Message.send('ON_AMI_LIST_PREVIOUS_DISABLE', this.idContainer, this.oPrevious); this.oPrevious.className = this.oPrevious.className + (this.oPrevious.className.length > 0 ? ' ' : '') + 'ami_resp_prev_disabled'; }else if(parseInt(this.aRequestData.offset) > 0 && this.oPrevious.className.indexOf('ami_resp_prev_disabled') >= 0){ AMI.Message.send('ON_AMI_LIST_PREVIOUS_ENABLE', this.idContainer, this.oPrevious); this.oPrevious.className = this.oPrevious.className.replace(/\s*ami_resp_prev_disabled/, ''); } } if(this.oNext != null && typeof(iDisableNext) != 'undefined'){ if(iDisableNext && this.oNext.className.indexOf('ami_resp_next_disabled') == -1){ AMI.Message.send('ON_AMI_LIST_NEXT_DISABLE', this.idContainer, this.oNext); this.oNext.className = this.oNext.className + (this.oNext.className.length > 0 ? ' ' : '') + 'ami_resp_next_disabled'; }else if(!iDisableNext && this.oNext.className.indexOf('ami_resp_next_disabled') >= 0){ AMI.Message.send('ON_AMI_LIST_NEXT_ENABLE', this.idContainer, this.oNext); this.oNext.className = this.oNext.className.replace(/\s*ami_resp_next_disabled/, ''); } } } this.setDebug = function(aReceivedData){ if(DEBUG_BY_IP && typeof(aReceivedData.debug) != 'undefined'){ if(this.oDebug == null){ this.oDebug = AMI.Browser.DOM.create('div', '', '', '', document.getElementById('ami_resp_outer_' + this.idContainer)); } this.oDebug.innerHTML = '
' + aReceivedData.debug + this.oDebug.innerHTML; } } this.load = function(lastAction){ if(typeof(lastAction) == 'undefined'){ this.lastAction = 'load'; }else{ this.lastAction = lastAction; } clearTimeout(this.refreshTimeout); if(this.oContainer != null){ this.showProgress(); var url = document.location.protocol + '//' + document.location.host + '/' + this.scriptName + '.' + this.scriptExt + '?'; var cnt = 0; for(var name in this.aRequestData){ if(name != 'refresh' && name != 'refreshMultiplier' && name != 'refreshType'){ url = url + (cnt++ > 0 ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(this.aRequestData[name]); } } AMI.HTTPRequest.getContent( 'GET', url, '', function(_this){ return function(state, content){ _this.onContentReceived(state, content); } }(this) ); } } this.onContentReceived = function(state, content){ if(state == 1){ this.hideProgress(); var aReceived = {}; if(content.indexOf('{') != 0){ aReceived.debug = 'Unknown data received for block ' + this.idContainer + ': ' + content; this.setDebug(aReceived); return; } aReceived = AMI.String.decodeJSON(content); var bDisableNext = true; if(typeof(aReceived) == 'object'){ if(typeof(aReceived.code) != 'undefined' && aReceived.code == -1){ document.getElementById('ami_resp_outer_' + this.idContainer).style.display = 'none'; document.getElementById('ami_resp_forbidden_' + this.idContainer).innerHTML += " '" + aReceived.message + "'"; document.getElementById('ami_resp_forbidden_' + this.idContainer).style.display = 'block'; return; } this.setDebug(aReceived); if(typeof(aReceived.data) == 'object' && typeof(aReceived.data.list) == 'object'){ this.lastRecordsCount = aReceived.data.list.length; if(aReceived.data.list.length == this.aRequestData.limit){ bDisableNext = false; } this.setListData(aReceived.data.list); this.playNext(); } } if(this.lastAction == 'next' && this.lastRecordsCount == 0){ this.aRequestData.offset = Math.max(0, parseInt(this.aRequestData.offset) - parseInt(this.aRequestData.limit)); } if(this.refreshType == 'next' && bDisableNext || this.refreshType == 'previous' && parseInt(this.aRequestData.offset) == 0){ this.playPause('pause'); } this.updatePrevNext(bDisableNext); } } this.setListData = function(aRowsData){ var oRowTemplate = document.getElementById(this.sRowTemplateId); var sRowTemplate = oRowTemplate == null ? '' : oRowTemplate.innerHTML; if(aRowsData.length && aRowsData.length > 0){ var content = ''; for(var i in aRowsData){ AMI.Message.send('ON_AMI_LIST_DRAW_ROW', this.idContainer, aRowsData[i]); aRowsData[i]['mod_link'] = this.aRequestData.mod_link; aRowsData[i]['ROW_NUMBER'] = i; content += AMI.Template.parse(sRowTemplate, aRowsData[i]); } this.fillBlockContent(content); } } this.fillBlockContent = function(content){ this.oContainer.innerHTML = content; } this.previousPage = function(bAutoAction){ if(typeof(bAutoAction) == 'undefined' || !bAutoAction){ this.playPause('pause'); } if(parseInt(this.aRequestData.offset) > 0){ this.aRequestData.offset = parseInt(this.aRequestData.offset) - parseInt(this.aRequestData.limit); this.load('previous'); } return false; } this.nextPage = function(bAutoAction){ if(typeof(bAutoAction) == 'undefined' || !bAutoAction){ this.playPause('pause'); } if(this.lastRecordsCount && this.lastRecordsCount == this.aRequestData.limit){ this.aRequestData.offset = parseInt(this.aRequestData.offset) + parseInt(this.aRequestData.limit); this.load('next'); } return false; } this.playPause = function(forceAction){ if(typeof(forceAction) == 'indefined'){ forceAction = 'none'; } if(this.refreshPaused && forceAction != 'pause'){ if(this.refreshType == 'next' && this.lastRecordsCount != this.aRequestData.limit){ return; } this.refreshPaused = false; this.oPlayPause.className = this.oPlayPause.className.replace(/\s*ami_resp_pause/, ''); this.refreshInterval = this.refreshIntervalInitial; this.refreshMaximum = this.refreshMaximumInitial; this.playNext(true); }else if(!this.refreshPaused && forceAction != 'play'){ this.refreshPaused = true; this.playStop(); this.oPlayPause.className = this.oPlayPause.className + ' ami_resp_pause'; } } this.playNext = function(bImmediately){ if(!this.refreshPaused && this.refreshInterval > 0 && this.refreshMaximum > 0){ var callback = null; if(this.refreshType == 'next'){ var callback = function(_this){return function(){_this.nextPage(true)}}(this); }else if(this.refreshType == 'previous'){ var callback = function(_this){return function(){_this.previousPage(true)}}(this); }else{ var callback = function(_this){return function(){_this.load()}}(this); } if(bImmediately){ this.refreshTimeout = setTimeout(callback, 200); }else{ this.refreshTimeout = setTimeout(callback, this.refreshInterval * 1000); } if(this.refreshMultiplier > 0){ this.refreshInterval *= this.refreshMultiplier; this.refreshMaximum--; } }else if(!this.refreshPaused){ this.playPause('pause'); } } this.playStop = function(){ clearTimeout(this.refreshTimeout); } this.init(); } AMI.UI.MediaBox = { iImageAnimateTime: 100, //ms iImageFadeInTime: 100, //ms bInitialized: false, oMediaShadow: null, oMediaBox: null, oLoader: null, oClose: null, oImageContainer: null, oImage: null, sImageType: 'image', iImageWidthAddon: 20, iImageHeightAddon: 20, hAnimateTimeout: null, iAnimateStepTime: null, iAnimateStepX: 0, iAnimateStepY: 0, iAnimateCurrentWidth: 0, iAnimateCurrentHeight: 0, iAnimateWidthTo: 0, iAnimateHeightTo: 0, iFadeInStep: 0, iFadeAnimationStep: 0, isOpening: false, isClosing: false, _iDocLeft: 0, _iDocTop: 0, _iWndWidth: 0, _iWndHeight: 0, _iTimeAnimateStop: 0, imageSizeCache: {}, oSkins: { __default: { 'skin': 'MediaBoxWhite', 'iWidthAddon': 20, 'iHeightAddon': 20 } }, addSkin: function(sSkin, aExtensions, iWidthAddon, iHeightAddon){ if(typeof(aExtensions) == 'object'){ for(var i = 0; i < aExtensions.length; i++){ this.oSkins[aExtensions[i]] = { 'skin': sSkin, 'iWidthAddon': iWidthAddon || 0, 'iHeightAddon':iHeightAddon || 0 }; } } }, open: function(imageUrl, imageWidth, imageHeight){ if(this.isOpening){ return; } this.isOpening = true; var self = this; if(!this.bInitialized){ this.oMediaShadow = AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadow', '', document.body); this.oMediaBox = AMI.Browser.DOM.create('DIV', '', 'MediaBox', '', document.body); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowL', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowR', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowT', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowB', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowLT', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowRT', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowLB', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_shadowRB', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_speckLT', '', this.oMediaBox); AMI.Browser.DOM.create('DIV', '', 'MediaBox_speckRB', '', this.oMediaBox); this.oClose = AMI.Browser.DOM.create('DIV', '', 'MediaBox_close', '', this.oMediaBox); this.oLoader = AMI.Browser.DOM.create('DIV', '', 'MediaBox_loader', '', this.oMediaBox); this.oImageContainer = AMI.Browser.DOM.create('DIV', '', 'MediaBox_container', '', this.oMediaBox); if(this.oMediaShadow != null && this.oMediaBox != null && this.oLoader != null){ this.oClose.onclick = this.oMediaShadow.onclick = function(){ self.close(); }; this.bInitialized = true; } } if(this.bInitialized){ this.oMediaShadow.style.display = 'block'; if(AMI.Browser.isIE || AMI.Browser.isIOS){ this.oMediaShadow.style.width = AMI.Browser.getDocumentWidth() + 'px'; this.oMediaShadow.style.height = AMI.Browser.getDocumentHeight() + 'px'; } this.startShadowAnimation(0); this.fadeInShadow(); itemExtension = ''; if(aMatches = imageUrl.match(/\.([a-zA-Z]{3,4})$/)){ var itemExtension = aMatches[1].toLowerCase(); }else if(aMatches = imageUrl.match(/\?sname=[^&]*\.([a-zA-Z]{3,4})&/)){ var itemExtension = aMatches[1].toLowerCase(); } var extension = typeof(this.oSkins[itemExtension]) != 'undefined' ? itemExtension : '__default'; this.oMediaBox.className = 'MediaBox ' + this.oSkins[extension]['skin']; this.iImageWidthAddon = parseInt(this.oSkins[extension]['iWidthAddon']); this.iImageHeightAddon = parseInt(this.oSkins[extension]['iHeightAddon']); if(AMI.Browser.isIE || AMI.Browser.isIOS){ this._iDocLeft = AMI.Browser.getDocumentLeft(); this._iDocTop = AMI.Browser.getDocumentTop(); } this._iWndWidth = AMI.Browser.getWindowWidth(); this._iWndHeight = AMI.Browser.getWindowHeight(); imageWidth = imageWidth || 170; imageHeight = imageHeight || 150; var ratio = this.getRatio(imageWidth, imageHeight); imageWidth = Math.floor(imageWidth * ratio); imageHeight = Math.floor(imageHeight * ratio); this.positionBox(imageWidth + this.iImageWidthAddon, imageHeight + this.iImageHeightAddon); if(itemExtension != 'swf'){ this.sImageType = 'image'; this.oLoader.style.display = 'block'; this.oImage = new Image(); this.oImage.className = 'MediaBox_image'; this.oImage.onload = function(){ self.displayImage(); } this.oImage.src = imageUrl; }else{ this.sImageType = 'FLASH'; this.oLoader.style.display = 'none'; this.oImageContainer.innerHTML = ''; } } }, close: function(){ if(!this.isClosing){ this.isClosing = true; clearTimeout(this.hAnimateTimeout); if(this.oImage){ this.oImage.onload = null; this.oImage = null; } this.oImageContainer.innerHTML = ''; this.oMediaBox.style.display = 'none'; this.startShadowAnimation(3) this.fadeOutShadow(); } }, getRatio: function(iImageWidth, iImageHeight){ var ratio = 1; if(iImageWidth > this._iWndWidth - this.iImageWidthAddon - 30 || iImageHeight > this._iWndHeight - this.iImageHeightAddon - 30){ var ratioX = (this._iWndWidth - this.iImageWidthAddon - 30) / iImageWidth; var ratioY = (this._iWndHeight - this.iImageHeightAddon - 30) / iImageHeight; ratio = Math.min(ratioX, ratioY); } return ratio; }, positionBox: function(width, height){ var deltaX = this._iDocLeft; var deltaY = this._iDocTop; this.oMediaBox.style.width = width + 'px'; this.oMediaBox.style.height = height + 'px'; this.oMediaBox.style.left = Math.max(this._iDocLeft + 10, parseInt((this._iWndWidth - width) / 2 + deltaX)) + 'px'; this.oMediaBox.style.top = Math.max(this._iDocTop + 10, parseInt((this._iWndHeight - height) / 2 + deltaY)) + 'px'; this.oMediaBox.style.display = 'block'; }, displayImage: function(){ var iNumberOfAnimateIterations = 13; if(AMI.Browser.isIE || AMI.Browser.isIOS){ var iNumberOfAnimateIterations = 3; } var ratio = this.getRatio(this.oImage.width, this.oImage.height); this.iAnimateWidthTo = Math.floor(this.oImage.width * ratio) + this.iImageWidthAddon; this.iAnimateHeightTo = Math.floor(this.oImage.height * ratio) + this.iImageHeightAddon; this.oImage.style.width = Math.floor(this.oImage.width * ratio) + 'px'; this.oImage.style.height = Math.floor(this.oImage.height * ratio) + 'px'; this.iAnimateStepX = Math.ceil((this.iAnimateWidthTo - parseInt(this.oMediaBox.style.width)) / iNumberOfAnimateIterations), this.iAnimateStepY = Math.ceil((this.iAnimateHeightTo - parseInt(this.oMediaBox.style.height)) / iNumberOfAnimateIterations), this.iAnimateStepTime = this.iImageAnimateTime / iNumberOfAnimateIterations; this.oLoader.style.display = 'none'; if(this.iAnimateStepX == 0 || this.iAnimateStepY == 0 || this.iAnimateStepTime == 0){ this.positionBox(this.iAnimateWidthTo, this.iAnimateHeightTo); this.oImage.width this.oImageContainer.appendChild(this.oImage); AMI.Browser.setOpacity(this.oImage, 0); this.iFadeInStep = 0; this.fadeIn(); }else{ this._iTimeAnimateStop = (new Date()).getTime() + this.iImageAnimateTime; this.animatePosition(); } }, animatePosition: function(){ var bFinalStep = (new Date()).getTime() > this._iTimeAnimateStop; if(!bFinalStep){ var width = parseInt(this.oMediaBox.style.width) + this.iAnimateStepX; var height = parseInt(this.oMediaBox.style.height) + this.iAnimateStepY; if(width >= this.iAnimateWidthTo || height >= this.iAnimateHeightTo){ width = this.iAnimateWidthTo; height = this.iAnimateHeightTo; bFinalStep = true; }else{ bFinalStep = false; this.positionBox(width, height); } } if(bFinalStep){ this.positionBox(this.iAnimateWidthTo, this.iAnimateHeightTo); this.oImageContainer.appendChild(this.oImage); AMI.Browser.setOpacity(this.oImage, 0); this.iFadeInStep = 0; this.fadeIn(); }else{ var self = this; this.hAnimateTimeout = setTimeout(function(){ self.animatePosition() }, this.iAnimateStepTime); } }, fadeIn: function(){ if(AMI.Browser.isIE || AMI.Browser.isIOS){ this.iFadeInStep += 3; }else{ this.iFadeInStep ++; } AMI.Browser.setOpacity(this.oImage, this.iFadeInStep / 10); if(this.iFadeInStep < 10){ var self = this; this.hAnimateTimeout = setTimeout(function(){ self.fadeIn() }, 12); }else{ AMI.Browser.setOpacity(this.oImage, 1); this.isOpening = true; } }, startShadowAnimation: function(iStartOpacity){ this.iFadeAnimationStep = 0; AMI.Browser.setOpacity(this.oMediaShadow, iStartOpacity); }, fadeInShadow: function(){ AMI.Browser.setOpacity(this.oMediaShadow, ++this.iFadeAnimationStep / 10); if(this.iFadeAnimationStep < (AMI.Browser.isIE || AMI.Browser.isIOS ? 2 : 3)){ var self = this; this.hAnimateTimeout = setTimeout(function(){ self.fadeInShadow() }, 24); } }, fadeOutShadow: function(){ AMI.Browser.setOpacity(this.oMediaShadow, (3 - ++this.iFadeAnimationStep) / 10); if(this.iFadeAnimationStep < (AMI.Browser.isIE || AMI.Browser.isIOS ? 2 : 3)){ var self = this; this.hAnimateTimeout = setTimeout(function(){ self.fadeOutShadow() }, 24); }else{ this.oMediaShadow.style.display = 'none'; this.isOpening = false; this.isClosing = false; } } } AMI.UI.MediaBox.addSkin('MediaBoxBlack', ['swf'], 0, 0); AMI.UI.Suggestion = function (fieldId, aRequestData, itemsSplitter){ this.aRequestData = aRequestData || {}; this.minimumFieldTextLength = 3; // Minimum length of text in parent field when suggestion should be shown this.fillRowsTimeout = 500; // Time between last key up and new rows load this.maxNameLength = 65; // Maximum length befor ... in dropdown list this.fieldId = fieldId; this.fieldObject = null; this.suggestionId = fieldId + '_suggestion'; this.suggestionObject = null; this.suggestionObjectShown = false; this.suggestionIframeObject = null; this.allowProcessing = true; this.showCauseOfArrows = false; this.rowObjects = new Array(); this.currentRow = -1; this.fillTimeout = null; this.itemsSplitter = typeof(itemsSplitter) != 'undefined' ? itemsSplitter : ''; this.lastFieldValueLength = 0; this.doStoreFieldValue = true; this.isFieldValueModified = false; this.storedFieldValue = ''; this.fieldLeadingSpaces = ''; this.itemInitialCaretPosition = 0; this.itemEndCaretPosition = 0; this.scriptName = 'ami_resp'; this.scriptExt = 'php'; // Initialize: Attach class events to text field and other actions this.init = function(){ this.fieldObject = document.getElementById(this.fieldId); this.storedFieldValue = this.fieldObject.value; this.lastFieldValueLength = this.storedFieldValue.length; AMI.Browser.Event.addHandler(this.fieldObject, 'mousedown', function(currentObject){return function(currentEvent){currentObject.onFieldMouseDown(currentEvent)}}(this)); AMI.Browser.Event.addHandler(this.fieldObject, 'keydown', function(currentObject){return function(currentEvent){currentObject.onFieldKeyDown(currentEvent)}}(this)); AMI.Browser.Event.addHandler(this.fieldObject, 'keyup', function(currentObject){return function(currentEvent){currentObject.onFieldKeyUp(currentEvent)}}(this)); AMI.Browser.Event.addHandler(this.fieldObject, 'blur', function(currentObject){return function(currentEvent){currentObject.onFieldBlur(currentEvent)}}(this)); AMI.Browser.Event.addHandler(this.fieldObject, 'focus', function(currentObject){return function(currentEvent){currentObject.showCauseOfArrows = true; currentObject.startShowObject(true)}}(this)); } this.setDebug = function(aReceived){ if(DEBUG_BY_IP && typeof(aReceived.debug) != 'undefined'){ var oDebugBlock = document.getElementById('amid'); if(oDebugBlock != null){ oDebugBlock.innerHTML = oDebugBlock.innerHTML + aReceived.debug; } } } // // Event handlers // this.onFieldMouseDown = function(currentEvent){ if((this.showCauseOfArrows || this.allowProcessing) && this.suggestionObjectShown && this.itemsSplitter != ''){ this.hideSuggestionObject(); } return true; } // Key down is used for arrow and escape processing this.onFieldKeyDown = function(currentEvent){ currentEvent = AMI.Browser.Event.validate(currentEvent); if(currentEvent.keyCode == 38 || currentEvent.keyCode == 40){ AMI.Browser.Event.stopProcessing(currentEvent); } if(!this.allowProcessing && !this.showCauseOfArrows){ return true; } if(this.suggestionObjectShown){ if(currentEvent.keyCode == 38 || currentEvent.keyCode == 40){ if(this.doStoreFieldValue){ this.storedFieldValue = this.fieldObject.value; this.doStoreFieldValue = false; } var rowIndex = this.currentRow + (currentEvent.keyCode == 40 ? 1 : -1); if(rowIndex > this.rowObjects.length - 1){ rowIndex = -1; }else if(rowIndex < -1){ rowIndex = this.rowObjects.length - 1; } this.selectRow(rowIndex, true); }else if(currentEvent.keyCode == 27){ this.resetFieldText(); this.closeSuggestionObject(); AMI.Browser.setCaretPosition(this.fieldObject, this.itemInitialCaretPosition); AMI.Browser.Event.stopProcessing(currentEvent); }else if(currentEvent.keyCode == 13){ var bSubmit = true; if(this.currentRow >= 0 && typeof(this.rowObjects[this.currentRow]) != 'undefined'){ if(this.rowObjects[this.currentRow].getAttribute('rowType') == 'result'){ var resultURL = this.rowObjects[this.currentRow].getAttribute('rowValue'); if(resultURL != ''){ document.location = resultURL; bSubmit = false; } } } this.doStoreFieldValue = true; this.hideSuggestionObject(); AMI.Browser.setCaretPosition(this.fieldObject, this.itemEndCaretPosition); AMI.Browser.Event.stopProcessing(currentEvent); if(bSubmit){ this.submitForm(); } }else if(this.itemsSplitter != '' && (currentEvent.keyCode == 35 || currentEvent.keyCode == 36 || currentEvent.keyCode == 37 || currentEvent.keyCode == 39)){ this.hideSuggestionObject(); } } return true; } // Key up shows/hides suggestion object when user typing this.onFieldKeyUp = function(currentEvent){ currentEvent = AMI.Browser.Event.validate(currentEvent); var doInitActionsCauseOfArrows = false; if(!this.showCauseOfArrows){ this.showCauseOfArrows = (!this.suggestionObjectShown && (currentEvent.keyCode == 38 || currentEvent.keyCode == 40)); doInitActionsCauseOfArrows = this.showCauseOfArrows; } if(!this.allowProcessing && !this.showCauseOfArrows){ return true; } if(currentEvent.keyCode == 27 || currentEvent.keyCode == 13){ return false; } this.startShowObject(doInitActionsCauseOfArrows); return true; } this.startShowObject = function(doInitActionsCauseOfArrows){ if(this.lastFieldValueLength != this.fieldObject.value.length){ this.doStoreFieldValue = true; this.lastFieldValueLength = this.fieldObject.value.length; }else if(!doInitActionsCauseOfArrows){ return false; } var currentItem = this.getEditedItemText(); if(currentItem.length >= this.minimumFieldTextLength){ this.itemInitialCaretPosition = AMI.Browser.getCaretPosition(this.fieldObject); // Create content div if(this.suggestionObject == null){ this.createSuggestionObject(); } // Fill rows clearTimeout(this.fillTimeout); if(doInitActionsCauseOfArrows){ this.fillRows(); }else{ this.fillTimeout = setTimeout(function(currentObject){return function(){currentObject.fillRows()}}(this), this.fillRowsTimeout); } }else{ this.hideSuggestionObject(); } } this.doNotCloseOnBlur = false; // Hide suggestion object upon blur this.onFieldBlur = function(currentEvent){ if(this.doNotCloseOnBlur){ this.doNotCloseOnBlur = false; return true; } if(!this.allowProcessing && !this.showCauseOfArrows){ return true; } this.hideSuggestionObject(); return true; } this.onSuggestionObjectClick = function(currentEvent){ currentEvent = AMI.Browser.Event.validate(currentEvent); var currentTarget = AMI.Browser.Event.getTarget(currentEvent); if(currentTarget.tagName){ if(currentTarget.tagName == 'A' && currentTarget.className == 'suggestionClose'){ this.resetFieldText(); this.closeSuggestionObject(); AMI.Browser.setCaretPosition(this.fieldObject, this.itemInitialCaretPosition); AMI.Browser.Event.stopProcessing(currentEvent); }else if(currentTarget.tagName == 'A'){ this.fieldObject.focus(); this.doNotCloseOnBlur = true; }else if(currentTarget.tagName == 'DIV'){ if(currentTarget.className.indexOf('suggestionRow') == 0){ currentIndex = currentTarget.getAttribute('rowIndex'); this.selectRow(currentIndex, true); this.hideSuggestionObject(); this.submitForm(); } } } return true; } // // Create / show / hide object functions // this.createSuggestionObject = function(){ contentDiv = document.createElement('div'); contentDiv.id = this.suggestionId; contentDiv.className = 'suggestionDiv'; var fieldPosition = AMI.Browser.getObjectPosition(this.fieldObject); contentDiv.style.left = fieldPosition[0] + 'px'; contentDiv.style.top = fieldPosition[1] + this.fieldObject.offsetHeight + 'px'; contentDiv.style.height = '12px'; contentDiv.onmousedown = function(currentObject){return function(currentEvent){currentObject.onSuggestionObjectClick(currentEvent)}}(this); this.suggestionObject = document.body.appendChild(contentDiv); } this.showSuggestionObject = function(bHasHistory, bHasResults){ this.suggestionObject.style.height = ((this.rowObjects.length - (!bHasHistory ? 1 : 0)) * 15 + (bHasResults ? 42 : 2)) + 'px'; if(!this.suggestionObjectShown && this.suggestionObject != null){ this.selectRow(-1, false); var fieldPosition = AMI.Browser.getObjectPosition(this.fieldObject); contentDiv.style.left = fieldPosition[0] + 'px'; this.suggestionObject.style.display = 'block'; var iScreenLeft = AMI.Browser.getDocumentLeft(); var iScreenRight = AMI.Browser.getWindowWidth() + iScreenLeft - 2; var iRightPoint = fieldPosition[0] + this.suggestionObject.offsetWidth; if(iRightPoint > iScreenRight){ contentDiv.style.left = fieldPosition[0] - (iRightPoint - iScreenRight) + 'px'; } this.suggestionObjectShown = true; } } this.hideSuggestionObject = function(){ this.showCauseOfArrows = false; clearTimeout(this.fillTimeout); if(this.suggestionObjectShown && this.suggestionObject != null){ this.suggestionObject.style.display = 'none'; this.suggestionObjectShown = false; } } this.closeSuggestionObject = function(){ this.allowProcessing = false; this.hideSuggestionObject(); } // // Manage data in object // this.fillRows = function(){ var url = document.location.protocol + '//' + document.location.host + '/' + this.scriptName + '.' + this.scriptExt + '?'; var cnt = 0; this.aRequestData['phrase'] = this.getEditedItemText(); for(var name in this.aRequestData){ url = url + (cnt++ > 0 ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(this.aRequestData[name]); } AMI.HTTPRequest.getContent( 'GET', url, '', function(_this){ return function(state, content){ _this.fillRowsCallback(state, content) } }(this) ); } this.fillRowsCallback = function(state, content){ if(state == 1){ this.currentRow = -1; this.rowObjects = new Array(); this.suggestionObject.innerHTML = ''; var fieldText = this.getEditedItemText(); var bHasHistory = false; var bHasResults = false; if(content.length){ var aReceived = {}; if(content.indexOf('{') != 0){ aReceived.debug = 'Unknown data received for block ' + this.idContainer + ': ' + content; this.setDebug(aReceived); return; } aReceived = AMI.String.decodeJSON(content); var bResultInserted = false; if(typeof(aReceived) == 'object' && typeof(aReceived.data) != 'undefined'){ this.setDebug(aReceived); for(var i = 0; i < aReceived.data.list.length; i++){ if(typeof(aReceived.data.list[i].query) != 'undefined'){ var name = this.trimText(aReceived.data.list[i].query); var itemValue = name; var itemType = 'suggestion'; var bExact = aReceived.data.list[i].query == fieldText; bHasHistory = true; }else{ name = '' + this.trimText(aReceived.data.list[i].name) + ''; itemValue = aReceived.data.list[i].link; itemType = 'result' bExact = false; bHasResults = true; } if(itemType == 'result' && !bResultInserted){ bResultInserted = true; var oResultsDiv = AMI.Browser.DOM.create('div', '', 'suggestionResult' + (i == 0 ? 'First' : ''), '', this.suggestionObject); oResultsDiv.innerHTML = 'Результаты поиска:'; } this.appendRow(name, itemValue, itemType, bExact); if(itemType == 'result' && i == aReceived.data.list.length - 1){ this.appendResultsRow(); } } } } if(bHasHistory || bHasResults){ var minWidthDiv = AMI.Browser.DOM.create('div', '', 'suggestionMinWidth', '', this.suggestionObject); minWidthDiv.style.width = this.fieldObject.offsetWidth - 3 + 'px'; this.showSuggestionObject(bHasHistory, bHasResults); }else{ this.hideSuggestionObject(); } } } this.trimText = function(data){ if(data.length > this.maxNameLength){ data = data.substr(0, this.maxNameLength) + '...'; } return data; } this.appendRow = function(itemText, itemValue, itemType, isExact){ var currentIndex = this.rowObjects.length; this.rowObjects[currentIndex] = AMI.Browser.DOM.create('div', this.fieldId + '_suggestionItem_' + currentIndex, 'suggestionRow' + (isExact ? ' suggestionRowExact' : ''), '', this.suggestionObject); this.rowObjects[currentIndex].innerHTML = itemText; this.rowObjects[currentIndex].setAttribute('rowIndex', currentIndex); this.rowObjects[currentIndex].setAttribute('rowValue', itemValue); this.rowObjects[currentIndex].setAttribute('rowType', itemType); this.rowObjects[currentIndex].setAttribute('rowExact', isExact ? '1' : '0'); this.rowObjects[currentIndex].onmouseover = function(currentObject, divIndex){return function(){currentObject.selectRow(divIndex, false)}}(this, currentIndex); } this.appendResultsRow = function(){ var currentIndex = this.rowObjects.length; this.rowObjects[currentIndex] = AMI.Browser.DOM.create('div', this.fieldId + '_suggestionItem_' + currentIndex, 'suggestionRow suggestionRowAllResults', '', this.suggestionObject); this.rowObjects[currentIndex].setAttribute('rowIndex', currentIndex); this.rowObjects[currentIndex].setAttribute('rowValue', ''); this.rowObjects[currentIndex].setAttribute('rowType', 'resultAll'); this.rowObjects[currentIndex].setAttribute('rowExact', '0'); this.rowObjects[currentIndex].onmouseover = function(currentObject, divIndex){return function(){currentObject.selectRow(divIndex, false)}}(this, currentIndex); var oResultsOthersLink = AMI.Browser.DOM.create('a', '', 'suggestionAllResults', '', this.rowObjects[currentIndex]); oResultsOthersLink.href = 'javascript:void(0)'; oResultsOthersLink.innerHTML = 'Все результаты »'; oResultsOthersLink.onclick = function(_this){return function(){_this.submitForm()}}(this); } this.selectRow = function(rowIndex, setRowText){ if(this.currentRow >= 0){ this.rowObjects[this.currentRow].className = 'suggestionRow' + (this.rowObjects[this.currentRow].getAttribute('rowExact') == '1' ? ' suggestionRowExact' : '') + (this.rowObjects[this.currentRow].getAttribute('rowType') == 'resultAll' ? ' suggestionRowAllResults' : ''); } if(rowIndex != null && rowIndex >= 0){ this.rowObjects[rowIndex].className = 'suggestionRowSelected' + (this.rowObjects[rowIndex].getAttribute('rowExact') == '1' ? ' suggestionRowExact' : '') + (this.rowObjects[rowIndex].getAttribute('rowType') == 'resultAll' ? ' suggestionRowAllResults' : ''); } if(setRowText){ if(rowIndex != null && rowIndex >= 0){ var rowType = this.rowObjects[rowIndex].getAttribute('rowType'); if(rowType == 'suggestion'){ this.setItemText(this.rowObjects[rowIndex].getAttribute('rowValue')); this.lastFieldValueLength = this.fieldObject.value.length; this.isFieldValueModified = true; }else{ this.resetFieldText(); } }else{ this.resetFieldText(); } } this.currentRow = rowIndex; } this.resetFieldText = function(){ if(this.isFieldValueModified){ var caretPosition = AMI.Browser.getCaretPosition(this.fieldObject); this.fieldObject.value = this.storedFieldValue; AMI.Browser.setCaretPosition(this.fieldObject, caretPosition); this.lastFieldValueLength = this.fieldObject.value.length; } } this.getEditedItemText = function(){ var itemText = ''; if(this.itemsSplitter != ''){ var splitterLength = this.itemsSplitter.length; var caretPosition = AMI.Browser.getCaretPosition(this.fieldObject); var items = this.fieldObject.value.split(this.itemsSplitter); var currentLength = 0; for(var i = 0; i < items.length; i++){ currentLength += items[i].length + (i > 0 ? splitterLength : 0); if(currentLength >= caretPosition){ itemText = items[i]; break; } } }else{ itemText = this.fieldObject.value; } itemText = itemText.replace(/^( *)(.*) *$/, function(currentObject){return function(wholeString, spaces, content){ currentObject.fieldLeadingSpaces = spaces; return content; }}(this)); return itemText; } this.setItemText = function(textValue){ if(this.itemsSplitter != ''){ var splitterLength = this.itemsSplitter.length; var caretPosition = AMI.Browser.getCaretPosition(this.fieldObject); var items = this.fieldObject.value.split(this.itemsSplitter); var currentLength = 0; var isReplaced = false; var result = ''; for(var i = 0; i < items.length; i++){ currentLength += items[i].length + (i > 0 ? splitterLength : 0); var itemValue = items[i]; if(!isReplaced && currentLength >= caretPosition){ itemValue = this.fieldLeadingSpaces + AMI.String.decodeHTMLSpecialChars(textValue); isReplaced = true; this.itemEndCaretPosition = currentLength + itemValue.length - items[i].length; } result += (result != '' ? this.itemsSplitter : '') + itemValue; } this.fieldObject.value = result; AMI.Browser.setCaretPosition(this.fieldObject, caretPosition); }else{ this.fieldObject.value = this.fieldLeadingSpaces + AMI.String.decodeHTMLSpecialChars(textValue); this.itemEndCaretPosition = this.fieldObject.value.length; } } this.submitForm = function(){ if(this.fieldObject != null && typeof(this.fieldObject.form) != 'undefined'){ this.fieldObject.form.submit(); } } // Do initializing this.init(); } AMI.UI.Multiselect = function(idField, iWidth, iRowHeight){ this.oField = document.getElementById(idField); this.oControl = null; this.lastOptionNumber = -1; this.lastOptionSelected = true; this.bAllowMoveSelection = false; this.hMoveSelectionStop = null; this.init = function(){ if(this.oField != null){ var width = iWidth || this.oField.offsetWidth; var height = this.oField.offsetHeight; var rowHeight = 18 || iRowHeight; var numRows = this.oField.getAttribute('size'); if(numRows != null && numRows > 0){ height = rowHeight * numRows; } this.oControl = AMI.Browser.DOM.create( 'DIV', '', 'mSelectFrame', 'width: ' + width + 'px; height: ' + height + 'px;' ); this.oControl = this.oField.parentNode.insertBefore(this.oControl, this.oField); if(typeof(this.oControl.onselectstart) != 'undefined'){ this.oControl.onselectstart = function(){ return false; }; } if(typeof(this.oControl.style.MozUserSelect) != 'undefined'){ this.oControl.style.MozUserSelect = 'none'; } this.oField.style.display = 'none'; for(i = 0; i < this.oField.options.length; i++){ var oOption = AMI.Browser.DOM.create( 'DIV', '', 'mSelectOption' + (this.oField.options[i].selected ? 'Selected' : ''), 'height: ' + rowHeight + 'px; line-height: ' + rowHeight + 'px;', this.oControl ); oOption.innerHTML = this.oField.options[i].text; oOption.setAttribute('optionNumber', i); oOption.setAttribute('optionValue', this.oField.options[i].value); oOption.onmousedown = function(_this){ return function(evt){_this.selectOption(evt, this)} }(this); oOption.onmouseup = function(_this){ return function(){_this.selectOptionStop(true)} }(this); oOption.onmouseover = function(_this){ return function(evt){_this.selectOptionOnMove(evt, this)} }(this); oOption.onmouseout = function(_this){ return function(){_this.selectOptionStop(false)} }(this); } } }; this.selectOption = function(evt, oOption){ var bSelected = oOption.className == 'mSelectOptionSelected'; var optionNumber = oOption.getAttribute('optionNumber'); evt = AMI.Browser.Event.validate(evt); if(evt.shiftKey && this.lastOptionNumber >= 0 && this.lastOptionNumber != optionNumber){ var iStartIndex = Math.min(optionNumber, this.lastOptionNumber); var iEndIndex = Math.max(optionNumber, this.lastOptionNumber); aOptions = this.oControl.getElementsByTagName('DIV'); for(var i = 0; i < aOptions.length; i++){ var iIntervalOptionNumber = aOptions[i].getAttribute('optionNumber'); if(iIntervalOptionNumber != null && iIntervalOptionNumber >= iStartIndex && iIntervalOptionNumber <= iEndIndex){ this.doSelectOption(aOptions[i], iIntervalOptionNumber, this.lastOptionSelected); } } }else{ this.doSelectOption(oOption, optionNumber, !bSelected); } if(this.lastOptionNumber == -1 || !evt.shiftKey){ this.lastOptionNumber = optionNumber; this.lastOptionSelected = this.oField.options[optionNumber].selected; } this.bAllowMoveSelection = true; } this.selectOptionOnMove = function(evt, oOption){ if(this.bAllowMoveSelection){ clearTimeout(this.hMoveSelectionStop); var optionNumber = oOption.getAttribute('optionNumber'); this.doSelectOption(oOption, optionNumber, this.lastOptionSelected); } } this.selectOptionStop = function(bImmediate){ if(bImmediate){ clearTimeout(this.hMoveSelectionStop); this.bAllowMoveSelection = false; }else{ this.hMoveSelectionStop = setTimeout(function(_this){ return function(){_this.bAllowMoveSelection = false;} }(this), 10); } } this.doSelectOption = function(oOption, optionNumber, bSelect){ if(bSelect){ oOption.className = 'mSelectOptionSelected'; this.oField.options[optionNumber].selected = true; }else{ oOption.className = 'mSelectOption'; this.oField.options[optionNumber].selected = false; } } this.init(); }