/**
 * JavaScript functions for work with website 
 * Copyright @ Nikida, Inc
 */

/*
  Marks:
  [SF-CS common] -- common for SilkFair application and Custom Store
*/

// -- VARIABLES --
var d = document;
var w = window;
var scrollerSize = 20;
var msgValidation = '';//<table class="compact w100">#{1}</table>
var cssValidationClass = 'alert_validation';

function humanize(string){
 string = string.gsub(/\[|\]|_|\d+/, " ").capitalize().gsub(/\s\w/, function(match){ return match[0].toUpperCase(); });
 var i = 0;
 var results = [];
 string = string.gsub(/(\w+) /, function(match){if (i <= 2) {results.push(match[0])} i++; });
 string = results.join(" ");
 return string.strip();
}

//Finding the size of the browser window
function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [ myWidth, myHeight ];
}

//Finding how far the window has been scrolled
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

//get Browser's page dimensions
function pageLeft (){ return d.body.scrollLeft; }
function pageTop (){
  return getScrollXY()[1];
}
function pageWidth () {
  if(d.all && !window.opera){
    //MSIE
    return d.body.offsetWidth-scrollerSize;//-pageLeft ();
  }else{
    return d.body.offsetWidth;
  }
}
function pageHeight () {
  return getWindowSize()[1];
}
function pageRight() {return  pageLeft()+pageWidth();}
function pageBottom() {return pageTop()+pageHeight();}

//Show map with frame
function Map(title, params) {
if (params) { params = '?' + params}
  var win = new Window({
    className: "mac_os_x", title: title, 
      width:750, height:450,
      showEffect: Element.show,
      hideEffect: Element.hide,
      minimizable: false,
      url: "/map/popup" + params}
  );
  win.keepMultiModalWindow=true;
  win.setDestroyOnClose(); 
  win.showCenter(false, 0);
}

//Show itemgallery with frame
function Gallery(title) {
  var win = new Window({
    className: "mac_os_x", title: title, 
      width:772, height:680,
      showEffect: Element.show,
      hideEffect: Element.hide,
      minimizable: false,
      url: "/gallery/popup"}
  );
  win.keepMultiModalWindow=true;
  win.setDestroyOnClose(); 
  win.showCenter(false, 0);
}

//Show colorbrowser with frame
//Used on Buying Guide page only
function ColorSearch(title) {
  var win = new Window({
    className: "mac_os_x", title: title, 
      width:772, height:680,
      showEffect: Element.show,
      hideEffect: Element.hide,
      minimizable: false,
      maximizable: false,
      url: "/gallery/popup_color_search"}
  );
  win.keepMultiModalWindow=true;
  win.setDestroyOnClose(); 
  win.showCenter(false, 0);
}

function toggle(obj) {
var el = $(obj);
 if ( el.style.display != 'none' ) {
   el.style.display = 'none';
 }
 else {
   el.style.display = '';
 }
}

/* toggle On/Off Element with Blind effect */
function toggleBlind(id){
  var obj = $(id);
  if (Element.visible(obj)){
    Effect.BlindUp(id);
  }else{
    Effect.BlindDown(id);
  }
}

var setValue = function(element, val) { $(element).value = val ; return false;} ;
var submitForm = function(form) { eval('document.' + form + '.submit()'); return false; } ; 

/**
 * Validation form
 */

function setMsgValidation(element, message){
  var tableRowTemplate = new Template('<tr><td><strong>#{label} :&nbsp;</strong></td><td class="red">&nbsp;#{text}</td></tr>\n');
  strResult = tableRowTemplate.evaluate({label: humanize(element.name), text: message.capitalize()});
  if (!msgValidation.include(strResult) ) {msgValidation += strResult;}
}

function alertMessage(text){
  var tableTemplate = new Template('<div class="AlertValidationContainer"><center><table class="compact smalltext" width="80%">#{text}</table></center></div>');
  Dialog.alert(tableTemplate.evaluate({text: text}), {windowParameters: {width:350, height:150, zIndex:900}, okLabel: " ",
    id: "AlertId", 
    ok:function(win) {return true;}});
}

function validate_form(form)
{
  //hasClassName == cssValidationClass
  msgValidation = "";
  toggleElement(form);
  myForm = form;// set global
  mytimer = setTimeout("toggleElement(myForm)", 2*1000);
  var obj = ( typeof form == "object" ) ? form : eval('document.' + form ) ;
  var isValid = new Boolean(true);
  var inputs = Form.getElements(obj);
  inputs.each(function(element){ if(element.id != '' && element.disabled != true && checkFormat(element, '') ) isValid = false;})
  if (isValid) {clearTimeout(mytimer)}
  if ( (Element.hasClassName(form, cssValidationClass)) && (msgValidation != "") ) {alertMessage(msgValidation)}
  return isValid ;
}

limit = function (f,count, max) {
  if (f.value.length > max) {
    f.value = f.value.substring(0, max);
  } else {
    count.value = max - f.value.length;
  }
}

/**
 * On/OFF HighLight Error fields
 */
function fieldHighLight(element, toggle, title )
{
  el = $(element).parentNode;
  if ($(el).nodeName.toUpperCase() == 'FIELDSET') el = $(el).parentNode;
  pseudoid = getPseudoId(element);
  titleid =  pseudoid != false  ? pseudoid : element ;  
  id = $(titleid).id + '_err';
  if ( toggle == 'on' ) { 
    title = title.replace(/^\s+|\s+$/,'') ;
    if ( !Element.hasClassName(el,'fieldWithErrors')) { 
      Element.addClassName(el, 'fieldWithErrors'); 
      if ( title != "null" ) { 
        $(el).title = title;
      }
    }
    if ( typeof($(id)) != "object" && title != "null" ) {
      new Insertion.Before(el, '<div id="'+id+'" class="errortitle" style="color: red">'+ title +'</div>');
    }
  } else {
    if ( $(id) != null) Element.remove(id);
    el = $(element).parentNode;
    if ($(el).nodeName.toUpperCase() == 'FIELDSET') el = $(el).parentNode;    
    Element.removeClassName(el, 'fieldWithErrors'); $(el).title = ''; 
  }
}
function fieldHigh(element, toggle){
  var hlClassName = "fieldHighlighted";
  elObj = $(element);
  if (toggle){
    if ( !Element.hasClassName(elObj, hlClassName)) { 
      Element.addClassName(elObj, hlClassName);
    }
  }else{
    Element.removeClassName(elObj, hlClassName);
  }
}

function checkFormat(element, type)
{
  var t = new Boolean(false);
  t = validateNode(element);
  if (t != false){ fieldHighLight(element, 'on', t); setMsgValidation(element, t); return true}
  return false
}

function getPseudoId(element)
{
  if ( !$(element) || $(element).attributes.validate == undefined ) return false;  
  var type = $(element).attributes.validate.nodeValue;
  if ( type == "" || type == undefined ) return false ;
  pseudoid = /\:id\s+([\w_]+)/.exec(type);
  if ( pseudoid == null ) return false;
  if ( typeof( $(pseudoid[1]) ) != "object") return false ;
  return pseudoid[1] ;
}

function validateNode(element)
{
  if ( !$(element) || $(element).attributes.validate == undefined || $(element).getAttribute('disableValidation', false) != null ) return false;  
  var type = $(element).attributes.validate.nodeValue;
  if ( type == "" || type == undefined ) return false ;

  var msg = new Boolean(false);
  var containerID = new Boolean(false);  
  sectionsRE = new RegExp("::");
  messageRE = new RegExp(":message");
  typesRE = new RegExp(/\s/);  
  sections = type.split(sectionsRE);
  var additioinalMsg = '' ;
  for(i=sections.length; i >= 0; i--)
  {
    if ( i == 0 )
    {
      sections[0] = sections[0].replace(/^\s|\s$/, '');
      fieldtypes = sections[0].split(typesRE);
      if (!fieldtypes.include('optional') || $F(element) != '') {
        fieldtypes.each(function(type) { if ( type!='' &&  msg == false ) { msg = validateValue(element, type, containerID ); } })
      }
    }
    else if ( messageRE.test(sections[i]) ) { additioinalMsg = sections[i].replace(messageRE, ''); additioinalMsg = additioinalMsg.replace(/^\s|\s$/, ''); }
    else if ( /:id/.test(sections[i]) ) { containerID = sections[i].replace(/:id/, ''); containerID = containerID.replace(/\s+/, ''); }
  }
  return  ( additioinalMsg !="" && msg != "" ) ? additioinalMsg : msg ;
}

function validateValue(element, type, containerID)
{
  var t = '' ; 
  isIntRE = new RegExp(/[^0-9]/);
  emailRE = new RegExp(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/);
  if (/\=/.test(type))
  {
    value = type.substr(1+type.indexOf("="), type.length);
    type = type.substr(0,type.indexOf("="));
  }
  if ( type == 'required' &&  ( $F(element) == '' || /^\s+$/.test($F(element)) ) ) {
      t = "Field is empty";    
  } else if ( type == 'notnull' &&  $F(element) == 0 ) {
      t = "Field can not be a null";    
  }  else if ( type == 'int' && isIntRE.test( $F(element) ) == true ) {
     t = "Invalid number format";
  } else if ( type == 'float'  && isNaN( $F(element) ) ) {
      t = "Invalid number format"; 
  } else if ( type == 'email'  && emailRE.test($F(element))==false ) {
      t = "Invalid email format";       
  } else if ( type == 'alphanumspace'  && !/^[0-9a-zA-Z\s]+$/.test($F(element)) ) {
      t = "Please use only letters (a-z) or numbers (0-9) or space only in this field";      
  } else if ( type == 'alphanumspacecolon'  && !/^[0-9a-zA-Z\s\:]+$/.test($F(element)) ) {
      t = "Please use only letters (a-z) or numbers (0-9) or space or : only in this field";      
  } else if ( type == 'alphanum'  && !/^[0-9a-zA-Z]+$/.test($F(element)) ) {
      t = "Please use only letters (a-z) or numbers (0-9) only in this field";            
  } else if ( type == 'phone'  && !/^[\+0-9\s\-\(\)]+$/.test($F(element)) ) {
      t = "Please use valid format for phone number";
  } else if ( type == 'notdefault'  && $F(element)=="default") {
      t = "Please select value";                        
  } else if ( type == 'maxlength'  && $F(element).length > value  ) {
      t = "Value can't be more than "+value+" symbol"+((value>1)?'s':'');                              
  } else if ( type == 'minlength'  && $F(element).length < value  ) {
      t = "Value can't be less than "+value+" symbol" + ((value>1)?'s':'');                                    
  } else if ( type == 'dateformat' ) {
      format = '';
      for(j=0; j<value.length; j++)
      {
        chr = value.substr(j,1);
        chr = chr.replace(/\//,'\\/'); 
        chr = chr.replace(/\./,'\\.');
        chr = chr.replace(/\-/,'\\-');
        chr = chr.replace(/\w/,'\\d');        
        format += chr;
      }
      format = eval('/^'+format+'$/') ;  
      if ( format.test($F(element)) ) return false;
      t = "Please use valid format for date"; 
  } else if ( type == 'date_afternow'  ){
      element=$(containerID);
      var els = $A(element.getElementsByTagName('select'));
      var myDate  = new Date();
      myDate.setDate(myDate.getDate()-1); // switch to yesterday to address time zone differences
      var date = new Array(); var nowdate = new Array();
      els.each(function(el){ 
        if ( /1/.test(el.id) ) { date[1]=$F(el); nowdate[1]= myDate.getFullYear(); }
        else if ( /2/.test(el.id) ) { date[2]=$F(el); nowdate[2]= myDate.getMonth()+1; }
        else if ( /3/.test(el.id) ) { date[3]=$F(el); nowdate[3]= myDate.getDate(); }
      })        
      if ( Date.parse( date.join(" ") ) < Date.parse( nowdate.join(" ") ) ) t = "Date should not be earlier than current date";
  } else if ( type == 'date_afterthat'  ){
      element=$(containerID);
      var els = $A(element.getElementsByTagName('select'));
      var date = new Array();
      els.each(function(el){ 
        if ( /1/.test(el.id) ) { date[1]=$F(el);}
        else if ( /2/.test(el.id) ) { date[2]=$F(el);}
        else if ( /3/.test(el.id) ) { date[3]=$F(el);}
      })        
      if ( Date.UTC(date[1], date[2]-1, date[3], 0, 0, 0, 0)  < value * 1000 ) t = "Date should not be earlier than current date";
  } else if (type == 'requiredany' && containerID != false ) {
      var checked = new Boolean(false);
      element=$(containerID);
      var els = $A(element.getElementsByTagName('input'));
      els.each(function(el){ if( el.checked == true && el.attributes.validate != undefined) { checked = true ; fieldHighLight(el, 'off',  '' ); } })  
      if ( checked == false ) t = "No selected options"; 
  } else return false ;
  return ( t !='' ) ? t : false ;
}


/************************************

	Custom Alert Demonstration
	version 1.0
	last revision: 02.02.2005
	steve@slayeroffice.com

	Should you improve upon this source please
	let me know so that I can update the version
	hosted at slayeroffice.

	Please leave this notice in tact!

************************************/

if(document.getElementById) {
  window.alert = function(txt) {
    Dialog.alert(txt, {windowParameters: {width:350, height:120}, okLabel: " ",
    id: "AlertId", 
    ok:function(win) {return true;}});   
  }
}

function removeCustomAlert() {
  document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

/* SelectConstructor */
function SelectConstructor(pid, target, arr, blank, selected)
{
  var goods = arr;
  var someNodeList = $(target).getElementsByTagName('option');
  var nodes = $A(someNodeList);
  nodes.each(function(node){ Element.remove(node); });	
  var i = 0 ;
  if (blank != null)
  {
    opt = new Option();	opt.value = blank[1]; opt.text = blank[0];	
    $(target).options[i++] = opt ;
  }

  goods.each(function(node){  
    if ( node[3] == $(pid).value ) {
      opt = new Option();
      opt.value = node[0];  
      opt.text =  node[1];
      opt.style.paddingLeft = 10 * ( node[4]-1 ) + "px"	;
//      if ( node[5] > 0 || node[2] == null ) opt.style.fontWeight="bold" ;
      if ( node[0] == selected ) opt.selected = "selected" ;
      $(target).options[i++] = opt ;
    }
  });	
}

/* used with SelectConstructor function */
setSubdirValidation = function(){
  if($('item_group_id').options.length > 1) {
     $('item_group_id').setAttribute('validate', 'required int notdefault :: :message Select subcategory');
     $('item_group_id').disabled = false;
  } else {
    $('item_group_id').setAttribute('validate', '');
    $('item_group_id').disabled = true;
  }
  fieldHighLight($('item_group_id'),'off', '');
}

function createModalBox(id) {
  d = document;
  if(d.getElementById("modalContainer")) return;
  mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  mObj.id = "modalContainer";
  //mObj.style.height = d.documentElement.scrollHeight + "px";
  Element.setStyle(mObj, {left:pageLeft()+"px", top:pageTop()+"px", width:pageWidth()+"px", height:pageHeight()+"px"});
    
  alertObj = mObj.appendChild(d.createElement("div"));
  alertObj.id = "modalBox";
  new Insertion.Before(alertObj, 
       '<iframe id="' + alertObj.id + '_iefix" '+
         'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
         'src="/blank.html" frameborder="0" scrolling="no"></iframe>');
  ieFix = $(alertObj.id+'_iefix');
  if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
  alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
  alertObj.style.display = "none";
}

function showModalBox(id, parentID, position) {
  var indentV = 10; //constant: vertical indent
  var pipkaWidth = 45;
  /* default id */
  if($(id) == null ) id = "modalBox";
  if(position == "undefined") position = [0,0];
  
  var parentObj = $(parentID);
  var alertObj  = $(id);
  var ieFix     = $(alertObj.id+'_iefix');
  
  //set Position
  if ($(parentID) == null ){
    //center the popup
    if (Element.getDimensions(alertObj).width > pageWidth()){
      alertObj.style.left = 0;
    }else{
      alertObj.style.left = (pageWidth() - Element.getDimensions(alertObj).width - pipkaWidth)/2;
    }
    if (Element.getDimensions(alertObj).height > pageHeight()){
      //! trick for IE
      alertObj.style.top = (0/(pageHeight() - Element.getDimensions(alertObj).height))+indentV;
    }else{
      alertObj.style.top = (pageHeight() - Element.getDimensions(alertObj).height)/2;
    }
    Element.setStyle(alertObj, {position:"absolute",zIndex:"4"});
  }else{
    //apply style [cumulativeOffset]
    var containerObj = alertObj.parentNode;
    var l = Position.cumulativeOffset(parentObj)[0] - Position.cumulativeOffset(containerObj)[0];
    var t = Position.cumulativeOffset(parentObj)[1] - Position.cumulativeOffset(containerObj)[1];
    alertObj.style.position  = "relative";
    Element.setStyle(alertObj, { left: l+position[0]+'px', top: t+position[1]+'px'});
  }
  // show, fix IE-bug
  Element.show(alertObj, ieFix);
  Element.show(ieFix);
  Element.setStyle(ieFix, {width:"1px", height:"1px"});
  if(d.all && !window.opera){ //MSIE
    Position.clone(alertObj, ieFix);
  }
  ieFix.style.zIndex = 1;
  alertObj.style.zIndex = 2;
}

/* unused
function closeModalBox(id){
  if( $(id) == null )return;
  var alertObj = $(id);
  var ieFix = $(alertObj.id+'_iefix');
  Element.remove(ieFix);
  Element.update(alertObj, "");
}
*/

//based on http://www.codelifter.com/main/javascript/capturemouseposition1.html
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
//var tempX = 0
//var tempY = 0

/* unused
function movePopup(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}
  setBounds('modalBox', tempX, tempY);
}
*/

/* used in unused movePopup function
function setBounds(id, tempX, tempY){
  $(id).style.top = tempY-120 + "px";
  if (tempX<512) {
    $(id).style.left = "400px";
  } else {
    $(id).style.left = "500px";
  }
}
*/

function getBounds(element)
{
  var left = element.offsetLeft;
  var top = element.offsetTop;
  for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
  {
    left += parent.offsetLeft;
    top += parent.offsetTop;
  }
  return {left: left, top: top, width: element.offsetWidth, height: element.offsetHeight};
}

function toggle_with_icon(id, el){
 if ( $(id).style.display == 'none' ) {
   Element.show(id);
   $(el).firstChild.src="/images/negative.gif";
 } else {
   Element.hide(id);
   $(el).firstChild.src="/images/plus.gif";   
 }
}

function toggle_with_arrow(id, el){
 if ( $(id).style.display == 'none' ) {
   Element.show(id);
   $(el).firstChild.src="/images/button_arrow_top.gif";
 } else {
   Element.hide(id);
   $(el).firstChild.src="/images/button_arrow_down.gif";
 }
}

//used for activateFeaturedShopsPopup only
/*
function createIEfix(id){
  var alertObj = $(id);
  new Insertion.Before(alertObj,
    '<iframe id="' + alertObj.id + '_iefix" '+
    'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
    'src="/blank.html" frameborder="0" scrolling="no"></iframe>');
  ieFix = $(alertObj.id+'_iefix');
  ieFix.style.zIndex = 1;
  alertObj.style.zIndex = 2;
  Element.show(ieFix);
  Position.clone(alertObj, ieFix);
}
*/

/* unused
function centerPopup(id) {
  var indentV = 10; //constant: vertical indent
  var pipkaWidth = 45;
  var d = document;
  
  if ( $(id) == null) {
    id = "modalBox";
  }
  
  var popBox = d.getElementById(id);
  var popBoxFC = popBox.firstChild;
  if(d.all && !window.opera){
    popBox.style.top = (d.body.offsetHeight - popBoxFC.offsetHeight)/2 + d.body.scrollTop + "px";
  }else{
    popBox.style.top = d.body.scrollTop + indentV + "px";
  }
  alertObj.style.left = (d.body.offsetWidth - popBoxFC.offsetWidth)/2 - pipkaWidth + d.body.scrollLeft + "px";
}
*/

/* Login menu (SF-CS common) */
function labelShow(obj, text, isPasswordField){
  var d = document;
  //Show Label
  if ($F(obj).strip() == ""){
    if(!d.all || window.opera){
      if (isPasswordField) {
        obj.type = "text";
      }
    }
    obj.value = text;
  }
}
/* Login menu (SF-CS common) */
function labelHide(obj, text, isPasswordField){
  var d = document;
  if(!d.all || window.opera){
    if (isPasswordField) {
      obj.type = 'password';
    }
  }
  //Hide Label
  if ($F(obj).strip() == text){
    obj.value = "";
  }
}

/* Site Tool Tabs (restored from [8704]): used in /mysilk/account/_order_acceptance_required.rhtml */
function showSitetool(id){
  //if ( $(id) == null ) return false;
  Element.show(id);
}
function hideSitetool(id){
  //if ( $(id) == null ) return false;
  Element.hide(id);
}

function hideEditButtons(){
  editButtons = $$("div#thread_container img.inlineEditButton");
  editButtons.each( function(editButton){
    Element.hide(editButton);
  });
}
function showEditButtons(){
  editButtons = $$("div#thread_container img.inlineEditButton");
  editButtons.each( function(editButton){
    Element.show(editButton);
  });
}

function create_script_element(el){
  if ( $(el) == null ) {
    o = document.createElement("SCRIPT");
    o.type = "text/javascript";
    o.id = el;
    o.src = el;
    $$('head').first().appendChild(o);
  } else if( $(el) != null && $(el).src != el ){
    $(el).src = el;
  }
}

/* used in unused function toggleValidation
disableValidation = function(target){
  $(target).setAttribute('disableValidation', 'disabled', false); fieldHighLight($(target),'off', '');
}
 */

/* used in unused function toggleValidation
enableValidation = function(target){
  if($(target).getAttribute('disableValidation', false) != null) $(target).removeAttribute('disableValidation', false);
} 
 */

/* #TODO: check! this function is redefined and not used
toggleValidation = function(switcher, values, targets ) {
  if( values.indexOf($F(switcher)) == -1 ) { 
    targets.each(function(el){ disableValidation(el) });
  } else {
    targets.each(function(el){ enableValidation(el); });
  }
}
 */

toggleStateField = function(switcher, target, textfiled) {
  values = ["United States"];
  if( values.indexOf($F(switcher)) == -1 ) {
    fieldHighLight($(target),'off', '');
    Element.hide(target);
    $(target).disabled = true;
    $(textfiled).disabled = false;
    Element.show(textfiled);
  } else {
    fieldHighLight($(textfiled),'off', '');
    Element.hide(textfiled);    
    $(textfiled).disabled = true;
    $(target).disabled = false;
    Element.show(target);
  }  
}

//form : pointer to form object
//name : submit-button name
toggleElement = function(form, name) {
  name = name === undefined ? "submit" : name;
  element = Form.getInputs(form, "image", name)[0];
  if (element == null) {return false;}
  if (element.getAttribute("disabled") == null){
    element.setAttribute("disabled", "disabled");
    new Effect.Opacity(element,
        { duration: 0.5,
          transition: Effect.Transitions.linear, 
          from: 1.0, to: 0.3 });
  }else{
    new Effect.Opacity(element,
        { duration: 0.5,
          transition: Effect.Transitions.linear, 
          from: 0.3, to: 1.0 });
    element.removeAttribute("disabled");
  }
}

video_player = function(id, flv, width, height) {
	var s1 = new SWFObject("/flash/flvplayer.swf","single",width,height,"7");
	s1.addParam("allowfullscreen","true");
	s1.addVariable("file",flv);
	s1.addVariable("width", width);
	s1.addVariable("height", height);
	s1.addVariable("streamscript","lighttpd");
	s1.addVariable("autostart","true");
	s1.addVariable("type","flv");
	s1.write(id);  
}

play_video_file = function (filename){
  video_player('swfContainer', filename, '480', '390');
}

/* === Video Popup === */
var vPopEnabled = true;
var vPopTimeout = 1*1000;

vPopPlayerShow = function (partial, path){
  if (!vPopEnabled){ return false; }
  vPopEnabled = false;
  Dialog.info(partial, {windowParameters: {className: 'alert', width:500, height:460}});
  var vPopTimer = setTimeout("play_video_file('" + path + "')", vPopTimeout);
}

vPopPlayerHide = function () {
  Element.update('swfContainer', '');
  Dialog.closeInfo();
  vPopEnabled = true;
}

function shiftWidgetPopTop(pop_id, widget_id){
  if (pop_id == null) {pop_id = "modalBox";}
  if (widget_id == null) {widget_id = "silkfair_store_widget";}
  height = Element.getDimensions(widget_id).height;
  yPos = $(pop_id).offsetTop;
  shift = yPos-(height/2);
  if (shift <= 0){shift = 0;}
  Element.setStyle(pop_id, {top:shift+"px"});
  ieFix = $(pop_id+'_iefix');
  Position.clone(pop_id, ieFix);
}

/* Custom Store Categories (SF-CS common) */
var roll = function(el, save_state){
  var menu_element =  $('menu_cc_'+el);
  if (!menu_element) return ;
  var left = menu_element.getAttribute('lft') * 1;
  var right = menu_element.getAttribute('rgt') * 1;
  if(left + 1 == right) return ;
  menu_element.toggleClassName('has_child');
  var closed = menu_element.hasClassName('has_child');
  if(closed) {
    $$('#CustomCategory li').each(function(node){
      var node_left = node.getAttribute('lft') * 1;
      if((node_left > left) && (node_left < right)){
         node.hide();
         var node_right = node.getAttribute('rgt') * 1;
         if(node_left + 1 < node_right )node.addClassName('has_child');
       }
    });
  } else {
    $$('#CustomCategory li.parent_id_'+el).each(Element.toggle); 
  }
  if( save_state == true ) { new Ajax.Request('/site/ajax_custom_category_switch/', {asynchronous:true, evalScripts:true,  method:'POST', parameters: 'id=' + el + '&turn=' + closed });  }
}

/* Expand-Collapse module */
function collapseList(obj, id){
  var cnCollapse = "collapse";
  var cnExpand = "expand";
  Element.toggle(id);
  var firstItem = Element.childElements(obj)[0];
  if (Element.visible(id)){
    Element.removeClassName(firstItem, cnCollapse);
    Element.addClassName(firstItem, cnExpand);
  }else{
    Element.removeClassName(firstItem, cnExpand);
    Element.addClassName(firstItem, cnCollapse);
  }
}

/* Tab-Menu Secondary module */
function selectTab(obj, id){
  var objTab = obj.parentNode;
  var objTabMenu = objTab.parentNode;
  var objContent = $(id).parentNode;
  // Operations with content
  var children = Element.childElements(objContent);
  //hide all
  children.each( function(child){
    Element.hide(child);
  });
  $(id).show();
  // Operations with Menu
  var tabs = Element.childElements(objTabMenu);
  //Off all
  tabs.each( function(tab){
    Element.removeClassName(tab, "on");
  });
  Element.addClassName(objTab, "on");
}

/* not currently used
function activateFeaturedShopsPopup(){
  d = document;
  if(d.getElementById("modalContainer")) document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
	bgObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	bgObj.id = "background";
	if(d.all) { bgObj.style.height = "1000px";
	} else { bgObj.style.height  = d.documentElement.scrollHeight + "px"; }
    bgObj.style.width   = d.documentElement.scrollWidth + "px"

	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	mObj.style.height = d.documentElement.scrollHeight + "px";
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";
	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

    new Ajax.Updater(alertObj, '/account/ajax_popup_featured_shops', {asynchronous:true, evalScripts:true});
    alertObj.style.top = "50"
    alertObj.style.left = "400"
    alertObj.style.visiblity="visible";
    
    alertObj.style.display = "block";
    createIEfix(bgObj.id);
    Element.scrollTo(alertObj);
}
*/

/* not currently used
function toggleMinichat(){
  var arrBtnStats = ['on', '&#9679; On', 'off', '&#9679; Off'];
  var objBtn = $('button_chat');
  // toggle mini chat elements
  $('minichat').toggle();
  $('minichat_change_size_td').toggle();
  $('minichat_headers_link_td').toggle();
  // toggle menu chat button
  if ( Element.visible('minichat') ){
    objBtn.removeClassName(arrBtnStats[2]);
    objBtn.addClassName(arrBtnStats[0]);
    objBtn.firstChild.innerHTML = arrBtnStats[1];
  }else{
    objBtn.removeClassName(arrBtnStats[0]);
    objBtn.addClassName(arrBtnStats[2]);
    objBtn.firstChild.innerHTML = arrBtnStats[3];
  }
}
*/

/* Top Search */
function TopSearch() {
  /* common vars */
  this.objSearch = $('form_top_search')['text'];
  this.objLabel = $('hidden_label');
  this.arrText = ['Search site for items now', 'Search booth for items now'];

  this.setLabel = function(index){
    this.objSearch.value = this.objLabel.innerHTML = this.arrText[index];
  }

  this.isEmpty = function(){
    if ( (this.objSearch.value.strip() == "") || (this.objSearch.value.strip() == this.objLabel.innerHTML) ){
      return true
    }
    return false
  }

  this.isReady = function(){/* is ready to send? */
    return !this.isEmpty()
  }

  this.toggleSearchLabel = function(st){
    if (st == true){
      if (this.objSearch.value == "") {this.objSearch.value = this.objLabel.innerHTML}
    }else{
      if (this.objSearch.value == this.objLabel.innerHTML) {this.objSearch.value = ""}
    }
  }

  /* toggle between 'Site' and 'Booth' search option */
  this.toggleRange = function(storeName, st){
    var arrControls = $$("#localized_store_search a");
    var objSeller = $("seller");
    var cn = "act";//active className for trigger
    if (st == true){
      //on = Booth
      objSeller.value = storeName;
      if ( this.isEmpty() ){ this.setLabel(1)}
      arrControls[0].removeClassName(cn);
      arrControls[1].addClassName(cn);
    }else{
      //off = Store
      objSeller.value = "";
      if ( this.isEmpty() ){ this.setLabel(0)}
      arrControls[1].removeClassName(cn);
      arrControls[0].addClassName(cn);
    }
  }
}
/* End: Top Search */

/* Forums page popup (General App & CustomStore) */
createDivWithId = function(id) {
  var objDiv = d.createElement("div");
  objDiv.id = id;
  return objDiv
}
createEnlargement = function() {
  var divC1 = createDivWithId("c1");
  var divClose = createDivWithId("closeenlargement");
  var divEnlar = createDivWithId("enlargement");
  var a = d.createElement("a");
  a.href = "#";
  a.innerHTML = "&nbsp;x&nbsp;";
  a.onclick = function(){close_enlargement(); return false};
  divClose.appendChild(a);
  divEnlar.appendChild(divClose);
  divEnlar.appendChild(divC1);
  d.getElementsByTagName("body")[0].appendChild(divEnlar)
}
//removed from _popup_img.rhtml
function show_image(file,width,height,num,menu,type){
  if ($('enlargement') == null) createEnlargement();
  xWidth ('enlargement',width + 6);
  xHeight ('enlargement',height + 6 + 20);
  xWidth ('c1',width);
  xHeight ('c1',height);
  xWidth ('closeenlargement',width);
  xInnerHtml('c1','<img src="'+file+'" width="'+width+'" height="'+height+'" border="0" />');
  pos_left = parseInt((xClientWidth()-width+3)/2);
  if (menu==0){ini=305}else{ini=500}
  if(type=='thread'){
    pos_top = ini+(num*43)
  }else{
    if (xScrollTop()==0){
      pos_top = ini + (num*60)
    }else{
      pos_top = (ini/2) + xScrollTop()
    }
  }
  xMoveTo('enlargement',pos_left,pos_top);
  setTimeout("xShow('enlargement')",20)
}

function close_enlargement(){
  xHide('enlargement')
}

/* function for minichat
   TODO: check usage */
function replaceDiv(divChat,divClose){
  var smalldiv = document.getElementById(divChat);
  var closediv = document.getElementById(divClose);
  closediv.style.position = "absolute"
  smalldiv.style.position = "absolute"
  closediv.style.display = "inline"
  smalldiv.style.width = "500px"
  smalldiv.style.height = "330px"
  smalldiv.style.right = "1px"
  return false;
}
