///////////////////////////////////////////////////////////////////////
//     This script was designed by Kapur Technologies Pvt Ltd        //
//     for Kapur Inc's list2shop.com                                 //
//                                                                   //
//                                                                   //
//     this program is copyrighted, you need prior written           //
//     permission to use or copy this program                           //
///////////////////////////////////////////////////////////////////////
//***************************************************************************************
//   edited by                    date                            purpose
//  Meenakshi                   4/9/09        a new fn show_highlight_msg is called at few places where showMsg was called .
//  Nidhi                       5/25/09       validate_othercomments() added
//******************************************************************************************



                     
                         
// RemoveStoreFromPrintList() // this function is called on unchecking of checkboxes next to stores in shopping list
// it adds the store name in the array list notToBePrintedStores as key (not as value)
                         
var notToBePrintedStores = new Array(); 
function toggleStoreFromPrintList(store_name, checkbox_object){
    //alert("store_name="+store_name+", checkbox_object.checked is:   ="+checkbox_object.checked);
    if(checkbox_object.checked){
        addStoreToPrintList(store_name);
    }else{
        removeStoreFromPrintList(store_name);
    }
}
        
function removeStoreFromPrintList(store_name){
    //alert("remove it: "+store_name);
    // First add it to notToBePrintedStores
    notToBePrintedStores[store_name]=1; //1 means true, don't print
    // Now show the message next to that store.
    show_highlight_msg(" &nbsp; "+getMessage(133)+" &nbsp; ", "courtesy", "601_"+store_name, "yellow");
    //alert(notToBePrintedStores);
    //alert(notToBePrintedStores[store_name]);
}                 
        
function addStoreToPrintList(store_name){
    //alert("add it : "+store_name);
    notToBePrintedStores[store_name]=0; //0 means false, so print
    // Now show the message next to that store.
    hide("msg_loc_601_"+store_name);
    //alert(notToBePrintedStores);

}                
                         
function toPrintStoreOrNot(store_name){
    if(notToBePrintedStores[store_name]!=undefined && notToBePrintedStores[store_name]==1){
        //alert("skip this store: "+store_name);
        return false;
    }
    else {
        //alert("print this store: "+store_name);
        return true;
    }
} 


var save_type=null;
function LinkedList() {
    this.firstNode = null;
    this.lastNode = null;
    this.insertAfter = insertAfter;
    this.insertBefore = insertBefore;
    this.insertBeginning = insertBeginning;
    this.insertEnd = insertEnd;
    this.remove = remove;
    this.status = status;
    this.swapAdjusent = swapAdjusent;
    this.swap = swap;
}

function node(val)
{
    this.val = val;
    this.next = null;
    this.prev = null;

}

function insertAfter(node, newNode) {
    newNode.prev = node;
    newNode.next = node.next;

    if (node.next == null) {
        this.lastNode = newNode;
    }
    else {
        node.next.prev = newNode;
    }
    node.next = newNode;
}

function insertBefore(node, newNode) {
    newNode.prev = node.prev;
    newNode.next = node;

    if (node.prev == null) {
        this.firstNode = newNode;
    }
    else {
        node.prev.next = newNode;
    }
    node.prev = newNode;
}

function insertBeginning(newNode) {
    if (this.firstNode == null) {
        this.firstNode = newNode;
        this.lastNode  = newNode;
        newNode.prev = null;
        newNode.next = null;
    }
    else {
        this.insertBefore(this.firstNode, newNode)
    }
}

function insertEnd(newNode) {
    if (this.lastNode == null) {
        this.insertBeginning(newNode);
    }
    else {
        this.insertAfter(this.lastNode, newNode);
    }
}


function swapAdjusent(above,below,direction)
{
    var before1 = above.prev;
    var after2 = below.next;
    // roll over type
    if(this.lastNode==above) 
    {
        //move last to top position
        if(direction=='up') 
        {
            this.lastNode.next = this.firstNode;
            this.firstNode.prev = this.lastNode;
            this.firstNode = this.lastNode;
            this.lastNode = this.lastNode.prev;
            this.lastNode.next = null;
            this.firstNode.prev = null;
        }
        else //move first to last position
        {
            this.firstNode.prev = this.lastNode;
            this.lastNode.next = this.firstNode;
            this.lastNode = this.firstNode;
            this.firstNode = this.firstNode.next;
            this.firstNode.prev = null;
            this.lastNode.next=null;
        }
    }else
    {
        below.prev = before1;
        above.next = after2;
		
        if(before1 == null)
        {
            this.firstNode = below;
            // alert('restting first node to:' +this.firstNode.val);
        }
        else
            before1.next = below;
		
        if(after2 == null)
            this.lastNode = above;
        else
            after2.prev = above;
		    
        above.prev = below;
        //alert('above.prev.val='+above.prev.val);
        below.next = above;
    }
    //alert('first ->'+this.firstNode.val+'\n second = '+this.firstNode.next.val);
}


function status()
{
    if (this.firstNode == null)
        return "null";
    var txt = "";
    var t = this.firstNode;
    txt = t.val;
    while(t.next != null)
    {
        t = t.next;
        txt = txt +' , ';
        txt = txt + t.val;
    }
    return txt;
}



function swap(node1, node2)
{
    //can't to data swap, so need to do actual swap
    var before1 = node1.prev;
    var after1 = node1.next;
    node1.prev = node2.prev;
    node1.next = node2.next;
    node2.prev = before1;
    node2.next = after1;
    if(before1 != null)
        before1.next = node2;
    else
        this.firstNode = node2;
    if(after1 != null)    
        after1.prev = node2;
    else
        this.lastNode = node2;
	    
    if(node1.prev != null)
        node1.prev.next = node1;
    else
        this.firstNode = node1;
	
	
    if(node1.next != null)
        node1.next.prev = node1;
    else
        this.lastNode = node1;

}

function remove(node) {
    if (node.prev == null) {
        this.firstNode = node.next;
    }
    else {
        node.prev.next = node.next;
    }
    if (node.next == null) {
        this.lastNode = node.prev;
    }
    else {
        node.next.prev = node.prev;
    }

    delete node;
}
//validations of three text boxes start
var errNum;
var errMsg;
function checkPriceFormat(priceValue)
{
    js_action();
    //   errNum = validatePrice(priceValue);
    //errNum = validateString(priceValue,0,10,true)
    errNum = validateString(priceValue,0,50)
    if(errNum != 1001)
    {
        if(errNum == 1013)
        {
            errMsg = getMessage(errNum)+ " in Price,so skipped" ;   
        }
        //        else if(errNum == 1017)
        else if(errNum == 1008)
        {
            errMsg = "Price "+ getMessage(errNum);   
        }
        else
        {
            errMsg =getMessage(errNum);
        }
        showDivError("err_div" , errMsg);//replaced invalidNumber_err
        document.getElementById('input_price').value="";
        document.getElementById('input_price').focus();
        return false;
    }
    else{
        return true;
    }
}
function checkUnitFormat(unitValue)
{
    js_action();
    //    errNum = validateUnit(unitValue);
    errNum =validateString(unitValue,0,50,true);
    if(errNum != 1001)
    {
        if(errNum == 1013)
        {
            errMsg = getMessage(errNum)+ " in Qty" ;   
        }
        else if(errNum == 1008)
        {
            errMsg = "Qty" + getMessage(errNum) ;   
        }
        else
        {
            errMsg =getMessage(errNum);
        }
        showDivError("err_div" , errMsg);//replaced invalidNumber_err
        document.getElementById('input_NoOfUnits').value="";
        document.getElementById('input_NoOfUnits').focus();
        return false;
    }
    else{
        return true;
    }
}
function checkCommentFormat(commentValue)
{
    js_action();
    //    errNum = validateText200(commentValue);
    errNum =validateString(commentValue,0,200,true)
    //      alert(errNum);
    if(errNum != 1001)
    {
        if(errNum == 1013)
        {
            errMsg =  " Invalid comment skipped" ;  // getMessage(errNum)+
        }
        else if(errNum == 1009)
        {
            errMsg = "Valid Comments" + getMessage(errNum) +", so skipped" ;   
        }
        else
        {
            errMsg =getMessage(errNum);
        }
        showDivError("err_div" , errMsg);//replaced invalidNumber_err
        document.getElementById('input_comments').value="";
        document.getElementById('input_comments').focus();
        return false;
    }
    else{
        return true;
    }
}
//validations of three text boxes end
function validate_othercomments(){
        //alert('validate_othercomments');
    sl_other_comment = document.getElementById('sl_other_comments').value
    errNum = validateString(sl_other_comment, 0, 1000);
        //alert(errNum);
    if(errNum != 1001)    {
        //        alert('errNum1=' +errNum);
        if(errNum == 1023) {
            //            alert('errNum-1023')
            errMsg = "Maximum 1000 characters allowed for other comments" ;   
        }
        else  {
            errMsg =getMessage(errNum);
        }
        showDivError("err_div" , errMsg);
        return false;
    }  
    return true;
}

function cleanAllDivs()
{
    
    //alert('trying to clean all divs');
        showMessage('msg_loc_500',' '); 
    showMessage('add_item_message',' '); 
    hide('err_div','');//replaced invalidNumber_err
    hide('msg_div','');
    hide('msg_login_to_favorite','');
}
//var urlSaveSL="/save_shopping_list.do?saveShoppingList=";   
var http=getHTTPObject();
function saveSL_handleHttpResponse() 
{
    //alert("inseide saveSL_handleHttpResponse() + response to saving obtained.");
    if(http.readyState==4)
    { 
        if(http.status==200 && saveSL_handleResponseFromServer(http.responseText)) 
        { 
            //alert("saveSL_handleHttpResponse(),save_type="+save_type+"http.responseText is : "+http.responseText);
            showSaveSLMsg();
            recordSLSave();
            // popitup('null?printStatus=noPrint');  
            show('discard_shopping_list');
        }
        //        else if(http.status == 500) {
        //	        alert("Session TimeOut. Unable To Process Your Request");
        //                //Process Further
        //	}    
        else 
        {   //error message or 
            //showDivError('msg_div', getMessage(107));    
        }
    }  //end if
} //end function
              

//to remove this function: not required now.
function saveSL_handleHttpResponse1()
{
    if(http.readyState==4)
    {
        if(http.status==200 && saveSL_handleResponseFromServer(http.responseText)){
            recordSLSave();  
        }
        else 
        {
            // showDivError('msg_div', 'Error in Shopping List saving, Try again');   ----Commentted because not required to show it to unreg user
        }
    }  //end if
} //end function
                                
                          
function saveSL_handleResponseFromServer(data)  
{  
    var result_array = new Array();
    result_array= data.split(",");
    if(stringTrim(result_array[0])=="reg user current shopping_list" ) 
    {
        document.getElementById("getSL_idInt").value=result_array[1]; 
        return true;
    }
    else if(stringTrim(result_array[0])=="saved for unreg"){
        js_action() ;
        return true;
    }
    else if(stringTrim(result_array[0])=="slEmpty" && save_type!='reg_user_new_sl_button' && save_type!='unreg_user_print' && save_type!='reg_user_auto_save_sl'){
        //alert("save_type="+save_type);
        showMsg('msg_div', getMessage(129));        
    }
    else if(stringTrim(result_array[0])=="sessionTimeOut"){
        location.href="logout.do";
    }
    return false;     
}
                                    
function popitup(urlSavePrintSL) {
    var newwindow = window.open(urlSavePrintSL,'name','height=600,width=800');
    if(newwindow){
        window.close();
        newwindow = window.open('print_shopping_list.do?printStatus=printSuccessful','name','height=600,width=800');
        if (window.focus) {
            newwindow.focus();
            return false;
        }
    }else
        showMsg('msg_div', getMessage(108));   
    return false
}//popitup() ends 
function saveShoppingListAjaxfun(form,saveSLStatus) { //this function makes ajax call,  urlSaveSL
    if(!validate_othercomments()){return;} // don't try to save or anything if comments are not validated as true
    js_action();
    try {
        save_type = saveSLStatus;
        //        alert("saveShoppingListAjaxfun(),saveSLStatus="+saveSLStatus);
        if(form!='noform'){
            var stringSL=prepareSelectionString();
            //alert("stringSL in saveShoppingListAjaxfun is :"+stringSL);
            var lastSL_idInt=document.getElementById("getSL_idInt").value;
            var param="saveShoppingList="+escape(stringSL)+"&getSL_idInt="+lastSL_idInt; 
            //        var urlSaveSL="save_shopping_list.do?"+param;
            var urlSaveSL="save_shopping_list.do";
            //    if(form=="regis_savePrintSLform" || form=="unregis_savePrintSLform"){
            //        param = param+"&toPrint=true";
            //    }
            //{
            //alert(" param= "+param) ;
            if(stringSL!=null && stringSL.length>=1 ){
                http.open("POST", urlSaveSL, true); 
                if(form=="regis_savePrintSLform" || form=="unregis_savePrintSLform"){
                    param = param+"&toPrint=true";
                }
                //if(form.id=="regis_savePrintSLform" || form.id=="unregis_savePrintSLform"){
                http.onreadystatechange=saveSL_handleHttpResponse;  
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.setRequestHeader("Content-length", param.length);
                http.setRequestHeader("Connection", "close");
                //alert("param="+param);
                  http.send(param);
                //                new print using javascript
                if(form=="regis_savePrintSLform" || form=="unregis_savePrintSLform"){
                    //the below line not required any more. the print popup itself will get the shopping list to print using prepareSLStringToPrint().
                    //shopping_list=stringSL; // set the shopping_list to be printed as from the shoppingList page
                    openPrintPopup();          
                }
            }else if(save_type!= 'reg_user_auto_save_sl'){
                showMsg('msg_div', getMessage(129));        
            }
        }
        //        else if(saveSLStatus =='reg_user_new_sl_button'){ //used for testing
        //            saveStatus();
        //        }
    }   catch (e) {
        //alert("inside catch exception="+e);
    }//end catch
} //end saveShoppingList()

function showSaveSLMsg(){  
    //alert("showSaveSLMsg(),save_type ="+save_type);
    if (save_type == 'reg_user_save_sl'){
        //    showMsg('msg_div', 'reg_user_save_sl'); //used for testing
        //showMsg('msg_div', getMessage(109)); 
        show_highlight_msg(" &nbsp; "+getMessage(109)+" &nbsp; ",'courtesy','500','yellow');        
        
    }
    if(save_type == 'reg_user_save_print_sl'){
        // showMsg('msg_div', 'reg_user_save_print_sl'); //used for testing
        //showMsg('msg_div', getMessage(109)); 
        show_highlight_msg(" &nbsp; "+getMessage(109)+" &nbsp; ",'courtesy','500',"yellow");        
        
    }
    if(save_type == 'reg_user_auto_save_sl'){
        //showMsg('msg_div', getMessage(110)); 
        show_highlight_msg(" &nbsp; "+getMessage(110)+" &nbsp; ",'success','500',"yellow");        
        
    }
    //    if(save_type == 'reg_user_new_sl_button'){  //used for testing
    //               showMsg('msg_div', 'reg_user_new_sl_button'); 
    //    }
    //    if(save_type == 'unreg_user_print'){  //used for testing 
    //        alert("saveStatus()");  
    //       showMsg('msg_div', 'Print success for unreg'); 
    //    }
}
/*function showDivForAddButton(){  //call this from addSelection() in sl.jsp to handle non-hiding of error messages if user press "Add to sl" button
    if((checkUnitFormat(document.getElementById('input_NoOfUnits').value)==false)
    ||( checkPriceFormat(document.getElementById('input_price').value)==false) 
       || (checkCommentFormat(document.getElementById('input_comments').value)==false))
        {
            show(err_div);
        }   
}*/          
