/*********************************************************************
*               ADD IMAGE FIELDS
**********************************************************************/
function createFileInput(textRef, maxInputs){
  textRef=textRef.previousSibling;
  noInputs=textRef.value;

  if(noInputs=='' || noInputs>maxInputs){
    return false;
  }

  insertBeforeNode=document.getElementById('insertBeforeThis');

  for(var i=0;i<noInputs;i++){

    // ---------------------- input file

    //create label
    labelRef=document.createElement('label');
    labelRef.className='fixed_width';
    labelRef.appendChild(document.createTextNode('Upload image '+(i+1)+' (only png or jpg):'));
    textRef.parentNode.insertBefore(labelRef,insertBeforeNode);

    //create br
    /*br1Ref=document.createElement('br');
    textRef.parentNode.insertBefore( br1Ref,insertBeforeNode);*/

    //create input
    inputRef=document.createElement('input');
    inputRef.name='product_secondary_images[]';
    inputRef.type='file';
    inputRef.size='30';
    inputRef.className='valign_input';
    textRef.parentNode.insertBefore(inputRef,insertBeforeNode);

    
    
    // ---------------------- input text

    //create label
    labelRef=document.createElement('label');
    labelRef.style.marginLeft="15px;";
    labelRef.appendChild(document.createTextNode('Alt Tag for image '+(i+1)+': '));
    textRef.parentNode.insertBefore(labelRef,insertBeforeNode);

    //create br
    /*br1Ref=document.createElement('br');
    textRef.parentNode.insertBefore( br1Ref,insertBeforeNode);*/

    //create input
    inputRef=document.createElement('input');
    inputRef.name='alt_product_secondary_images[]';
    inputRef.type='text';
    inputRef.size='30';
    inputRef.className='valign_input';
    textRef.parentNode.insertBefore(inputRef,insertBeforeNode);

    //create br
    br2Ref=document.createElement('br');
    textRef.parentNode.insertBefore( br2Ref,insertBeforeNode);

    //create br
    br3Ref=document.createElement('br');
    textRef.parentNode.insertBefore( br3Ref,insertBeforeNode);
    
    
  }//end for

    //delete elements
    textRef.parentNode.removeChild(textRef.previousSibling.previousSibling); //label
    textRef.parentNode.removeChild(textRef.nextSibling);//a ref
    textRef.parentNode.removeChild(textRef);//input

}//end function createFileInput


function kH(e) {
    var pK = e ? e.which : window.event.keyCode;
    return pK != 13;
}
document.onkeypress = kH;


/*******************************************************************************
*
*                                   SECTION LINKS
*
*******************************************************************************/


close_open_menu=function(imgRef,action){
  if(action=='close'){
    document.getElementById('section_links').style.display='none';
    document.getElementById('center_content').style.width='100%';

    imgRef.alt='open current links list';
    imgRef.title='open current links list';
    imgRef.src='includes_tpl/images/section_links_open.gif';
    imgRef.onclick=function(){close_open_menu(this,'open');};
  }
  if(action=='open'){
    document.getElementById('section_links').style.display='block';
    document.getElementById('center_content').style.width='83%';
    imgRef.alt='open current links list';
    imgRef.title='open current links list';
    imgRef.src='includes_tpl/images/section_links_close.gif';
    imgRef.onclick=function(){close_open_menu(this,'close');};
  }

}//end function close_open_menu


close_open_help=function(imgRef,action){
  //div ref
  ddRef=get_prev_next_Element(imgRef.parentNode, 'DD', 'next');
  divRef=ddRef.getElementsByTagName('div')[0];
  if(action=='close'){

    Effect.BlindUp(divRef,{duration:1});
    imgRef.alt='close_help';
    imgRef.title='close_help';
    imgRef.onclick=function(){close_open_help(this,'open');};
  }
  if(action=='open'){
    Effect.BlindDown(divRef,{duration:1});
    imgRef.alt='open help';
    imgRef.title='open help';
    imgRef.onclick=function(){close_open_help(this,'close');};
  }

}//end function close_open_menu




/*******************************************************************************
*
*                            MANAGE PRODUCTS
*
*******************************************************************************/

enable_disable_field=function(inputRef,fieldId){
   var fieldToActOn=document.getElementById(fieldId);

   if(inputRef.checked==true){
     fieldToActOn.disabled=true;
   }
   else{
     fieldToActOn.disabled=false;
   }
}



viewImage = function(imgPath,width, height){
    var htmlContent='<img src="'+imgPath+'" />';

    var newWidth=parseInt(width)+30;
    var newHeight=parseInt(height)+50;

    show_details(htmlContent,newWidth, newHeight);
}


/*******************************************************************************
*
*                            MANAGE DISCOUNTS
*
*******************************************************************************/
display_free_products=function(selectRef, showDivId){
   divRef=document.getElementById(showDivId);

   if(selectRef.value=='free product(s)'){
    divRef.style.display='block';
    divRef.getElementsByTagName('select')[0].disabled=false;
    selectRef.form.discount_amount.value=0;

   }
   else{
    divRef.style.display='none';
    divRef.getElementsByTagName('select')[0].disabled=true;
   }
}//end function display_free_products




/*******************************************************************************
*
*                               MANAGE SETTINGS
*
*******************************************************************************/

function show_div(){
    if(document.getElementById('new_pass')){
          div_src=document.getElementById('new_pass');
               if(document.getElementById('new_pass_checkbox').checked==false){
                div_src.style.display='none';
               }
               else{
                  div_src.style.display='block';
               }
    }
}//end function

if (window.addEventListener){
     window.addEventListener('load', show_div, false);
}
else{
     window.attachEvent('onload', show_div);
}


/********************************************************************************
*                           MANAGE PRODUCT ATTRIBUTES   
*********************************************************************************/
var newRecordInfo={makes: {fieldsName:['manufacturer']},                  
                   screen_sizes: {fieldsName:['screen_size']},
                   delivery_charges: {fieldsName:['num_products_small','num_products_large','charge']},
                   delivery_charges_speed: {fieldsName:['description','charge']},
                   delivery_charges_zipcode: {fieldsName:['description','charge']},
                   delivery_dates_text: {fieldsName:['day_of_week','specific_date','hour','text']}
                  }
    //alert(newRecordInfo.test1.fieldsName.length);

/* ---------------------------editRecord---------------------------------*/

function editRecord(inputRef){
    //get reference to tr
    var trRef=inputRef.parentNode.parentNode;
    var recordId=trRef.title;

    //change text to input
    for(var i=0, noCels=trRef.childNodes.length;i<noCels;i++){
        if(trRef.childNodes[i].className=='field'){
            var newInputRef=document.createElement('input');
            newInputRef.type='text';
            newInputRef.size='25';            
            newInputRef.name=trRef.childNodes[i].title;
            newInputRef.value=trRef.childNodes[i].firstChild.nodeValue;
            newInputRef.oldValue=trRef.childNodes[i].firstChild.nodeValue;

            //delete textnode and insert input
            trRef.childNodes[i].firstChild.parentNode.removeChild( trRef.childNodes[i].firstChild);
            trRef.childNodes[i].appendChild(newInputRef);
        }
    }

    //change input type with cancel and add a save input
    inputRef.name='cancel';
    inputRef.value='cancel';
    inputRef.onclick=function(){cancelEdit(this);};

    var saveInputRef=document.createElement('input');
    saveInputRef.type='button';
    saveInputRef.name='save';
    saveInputRef.value='save';
    saveInputRef.onclick=function(){saveRecord(this)}

    inputRef.parentNode.insertBefore(saveInputRef, inputRef.nextSibling);
}

/* ---------------------------cancelEdit---------------------------------*/

function cancelEdit(inputRef){
   //get reference to tr
    var trRef=inputRef.parentNode.parentNode;
    var recordId=trRef.title;

    //change input to text
    for(var i=0, noCels=trRef.childNodes.length;i<noCels;i++){
        if(trRef.childNodes[i].className=='field'){
            var textRef=document.createTextNode(trRef.childNodes[i].firstChild.oldValue);

            //delete input and insert textNode
            trRef.childNodes[i].firstChild.parentNode.removeChild( trRef.childNodes[i].firstChild);
            trRef.childNodes[i].appendChild(textRef);
        }
    }

    //change input type with cancel and delete save input
    inputRef.name='edit';
    inputRef.value='edit';
    inputRef.onclick=function(){editRecord(this);};

    //delete save button
    inputRef.parentNode.removeChild(inputRef.nextSibling);
}



/* ---------------------------addRecord---------------------------------*/

function addRecord(tableName){
   var tableRef=document.getElementById(tableName);

   var newTrRef=document.createElement('tr');
   newTrRef.title='';
   tableRef.appendChild(newTrRef);

   //return;

   for(var i=0;i<newRecordInfo[tableName].fieldsName.length;i++){
       var newTdRef=document.createElement('td');
       newTdRef.className='field';

       var newInputRef=document.createElement('input');
       newInputRef.type='text';
       newInputRef.size='25';
       newInputRef.name=newRecordInfo[tableName].fieldsName[i];
       newInputRef.value='';

       newTrRef.appendChild(newTdRef);
       newTdRef.appendChild(newInputRef);
   }

   //add action field
   var newTdRefAction=document.createElement('td');
   newTdRefAction.className='actionField';

   var saveInputRef=document.createElement('input');
   saveInputRef.type='button';
   saveInputRef.name='save';
   saveInputRef.value='save';
   saveInputRef.onclick=function(){saveRecord(this)}

   var deleteInputRef=document.createElement('input');
   deleteInputRef.type='button';
   deleteInputRef.name='delete';
   deleteInputRef.value='delete';
   deleteInputRef.onclick=function(){deleteRecord(this)}

   newTdRefAction.appendChild(saveInputRef);
   newTdRefAction.appendChild(deleteInputRef);

   newTrRef.appendChild(newTdRefAction);


}


/* ---------------------------deleteRecord---------------------------------*/
function deleteRecord(inputRef){
   //get reference to tr
   var trRef=inputRef.parentNode.parentNode;
   var recordId=trRef.title;
   var selectName=trRef.parentNode.id;

   var rowInfo={recordId:recordId,selectName:selectName};

   //new record-delete only html
   if(recordId==''){
      trRef.parentNode.removeChild(trRef);
   }
   //delete from database too
   else{
      trRef.parentNode.removeChild(trRef);
      deleteOptionRequest(rowInfo);
   }
}


/* ---------------------------saveRecord---------------------------------*/
function saveRecord(inputRef){
   //get reference to tr
   var trRef=inputRef.parentNode.parentNode;
   var recordId=trRef.title;
   var attrName=trRef.parentNode.id;
   
   
   //get tbody id
   var attr_name=trRef.parentNode.id;

   var attr_values=new Array();

   for(var i=0;i<newRecordInfo[attr_name]['fieldsName'].length;i++){
      var inputName=newRecordInfo[attr_name]['fieldsName'][i]; 
      attr_values[inputName]=trRef.getElementsByTagName('input')[i].value;
   }

   var attrValue=js_array_to_php_array(attr_values);
   var rowInfo={recordId:recordId,attrName:attrName,attrValue:attrValue};

   //alert(optionValue);

   if(attrValue==''){
    return;
   }

   //new record-insert Record
   if(recordId==''){
     addOptionRequest(rowInfo);
   }
   //update Record
   else{
     //alert(test);
     editOptionRequest(rowInfo);
   }
}


//http://blogs.vinuthomas.com/2006/05/19/javascript-serialize-js-array-into-php/
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie
// from PHP like this:
//    &lt;?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?&gt;
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
function js_array_to_php_array (a){
  var a_php = "";
  var total = 0;

    for (var key in a){
        if(typeof a[key] == 'string')
        {
            ++ total;
            a_php = a_php + "s:" +String(key).length + ":\"" + String(key) + "\";s:" +String(a[key]).length + ":\"" + String(a[key]) + "\";";
        }
    }

    a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}



/*******************************************************************************
*
*                               MANAGE ORDERS
*
*******************************************************************************/

function sendSMS(phone){
  var divRef=document.getElementById('details');

  divRef.style.width="260px";
  divRef.style.height="280px";

  var formRef=divRef.getElementsByTagName('form')[0];
  formRef.to.value=phone;
  position_div_viewport(divRef, 250, 250+20);
  divRef.style.display="block";
}


function show_div_msg(selectRef){
    var divRef=document.getElementById('details');

    divRef.style.width="200px";
    divRef.style.height="230px";
    
    divRef.style.position="absolute";
    divRef.style.top="0px";
    divRef.style.right="30px";

    if(selectRef.value=='Canceled'){
         divRef.style.display="block";
    }
    else{        
        divRef.style.display="none";
    }
}

function toggleHelp(nb) {//asd
	var display = document.getElementById('showHelp'+nb).style.display;
	display = display=='none'?'block':'none';
	document.getElementById('showHelp'+nb).style.display=display;
}

function setRecommendedProduct(cb) {//asd
	ajaxreq('ajax.php',false,'recommendId='+cb.value+'&recommend='+(cb.checked?1:0));
}
function setBestSellerProduct(cb) {//asd
	ajaxreq('ajax.php',false,'bestsellerId='+cb.value+'&bestseller='+(cb.checked?1:0));
}
function setLatestProduct(cb) {//asd
	ajaxreq('ajax.php',false,'latestId='+cb.value+'&latest='+(cb.checked?1:0));
}

function putTextSample(textarea,id) {//asd
	if(textarea.value.match(/<font|"font|'font|;font|=font/i)) {
		alert('Please do not use fonts in the text');
		return;
	}
	document.getElementById(id).innerHTML=textarea.value;
}



