if(typeof $jq == 'undefined') {
   var $jq = jQuery.noConflict()
}



//  S T R I P   I T E M 
function  stripitem(item) {

    delete item['price_each']
    delete item['weight_each']
    delete item['weight']
    delete item['id']
    delete item['shipto']

return item

}



//  S T R I P   C A R T
function  stripproducts(products){

    for(var j in products)
        products[j] = stripitem(products[j])

return products

}



//  E N C O D E   I T E M (construct a get string)
function  encodeitem(item) {
    var o = ''
    
    for (var k in item)
        o += '&' + k + '=' + escape(   item [k]  )
    
return o

}



//   E N C O D E   P R O D U C T S
function  encodeproducts(products) {

    sendfoxy('','',devnull)

    var products = stripproducts(products)

    var o = ''
    
    for (var j in products) {
    
        for (var k in products[j]) {
            o += '&' + (parseInt(j) + 1) + ':' + k + '=' + escape(products[j][k])
        }
    
    }


      
return o

}



//   F L A T T E N   I T E M
function  flattenitem(item) {

    var options = item['options']
    
//    if(typeof options['id'] !== 'undefined'){
//        delete options['id']  // solution to thorn in side...
//    }

    delete item['options']

    for(var k in options)
        item[k] = options[k]

return item

}



//   F L A T T E N   C A R T
function  flattencart(cart) {

    for(var j in cart['products'])
        cart['products'][j] = flattenitem( cart['products'][j] )

return cart

}



//  R E M O V E   I T E M
function  removeitem(products) {

    for (var j in products)
        products[j]['x'] = removelink( products[j]['id'] )

return products

}



//   R E M O V E  L I N K
function  removelink(id) {

    // <a href="javascript: sendfoxy('&cart=empty', '', discview)">clear</a>

    var o = ''

    o += '<a href="'
    o += 'javascript: sendfoxy('
    o += "'&cart=update', "
    o += "'&id="  +  id
    o += "&quantity=0', "
    o += 'discview, ' 
    o += "'remove link')"
    o += '">'
    o += 'remove'
    o += '</a>'

return o

}



//    I D
function  id(id)
{ return document.getElementById( id ) }



//    R E Q U E S T   T O   J A V A S C R I P T
function  r2j() {
    
    var obj = new Object
    
    obj['name']                  =   id('name').value
    obj['code']                  =   id('code').value
    obj['resident']              =   id('resident').value
    obj['member']                =   id('member').value
    obj['start_date']            =   id('start_date').value
    obj['price']                 =   id('price').value
    obj['original_price']        =   id('price').value
    obj['category']              =   id('category').value
    obj['student_first_name']    =   id('student_first_name').value
    obj['student_last_name']     =   id('student_last_name').value
    obj['student_age']           =   id('student_age').value
    obj['unique']                =   new Date().getTime()
    obj['reg_id']                =   id('code').value + '-' + id('student_first_name').value + '-' + id('student_last_name').value + '-' + id('student_age').value

    regID = id('code').value + '-' + id('student_first_name').value + '-' + id('student_last_name').value + '-' + id('student_age').value

return obj

}



//    V A L I D A T E   &   P R E V E N T   D U P L I C A T E S
function  validate(cart) 
{
    for (var i in cart) {
        if  (cart[i]['reg id'] == regID) {
        
            return 'invalid'
        
        }
    }
}



//    I S   T H I S   D I S C O U N T A B L E ? 
function  discountable (item)
{

        if ('Discovery'.toLowerCase() !== item['category'].toLowerCase()) {
            return  false
        }

        if ('Yes'.toLowerCase() !== item['resident'].toLowerCase()) {
            return  false
        }

return true
}





//    F I L T E R   -  I N 
function  filterin(cart) {

    var D = new Array

    for(var i in cart) {
        if(discountable(cart[i])) {
            D.push(cart[i])
        }
    }

return D;

}




//    F I L T E R   -  O U T 
function  filterout(cart) {

    var D = new Array

    for(var i in cart) {
        if(!discountable(cart[i])) {
            D.push(cart[i])
        }
    }

return D;

}




//   C O M P A R I S O N    O P E R A T O R    F O R    S O R T I N G
function comp(a,b)
{ return (a['price'] - b['price']) }



//   D I S C O U N T
function  discount(products) {

    var D = new Array

    if(0  ==  products.length)
        return D
     
    // reset some things
    for (var i in products) {
        delete products[i]['discount']
        products[i]['price'] = products[i]['original price']
    }

//alert(pra(products))    
     
    //  split: discountable | not    via  'DEFAULT'
    var inn = filterin(products)
    var out = filterout(products)
    inn.sort(comp)


    //  collect discounted's  into  $discounted[]
    var counter = 0
    for( var i in inn ) {
        
        if(++counter > inn.length / 2) break;
        
        inn[i]['discount']   =   'Yes{p-' + inn[i]['original price'] / 2 + '}'

    }
    
    //  re-union...
    var products = inn.concat(out)
    sendfoxy( '&empty=true', encodeproducts(products), showme, 'discount' )

return products

}



//   B E A U T I F U L    C O M M E N T    A B O U T    N O T H I N G
function  devnull(cart) {}



//  S H O W   C A R T
function  showme(cart) {

    removeitem(cart['products'])

    id('cartlist').innerHTML = fcCartView( cart )
    
    fc_UpdateCart(FoxyDomain)
    
}



//   D I S C O U N T   &   V I E W
function  discview(cart) { 

    (cart['products'].length == 0)
            ? 
        showme(cart)
            :
        discount( cart['products'] )
    
}



//   S E N D F O X Y 
function  sendfoxy(cmd, getstr, func, msg) {

    var url = 'https://mariamitchell.foxycart.com/cart?output=json&callback=?' + fc_AddSession() + cmd + getstr

    /* // D E B U G  /  V E R B O S E
    if ('undefined' !== typeof(msg)){
           alert("sendfoxy..."
           +  "\n\nurl:\t"     +  url
           +  "\n\ncmd:\t"     +  cmd
           +  "\n\ngetstr:\t"  +  getstr
           +  "\n\nfunc:\t"    +  func
           +  "\n\nclient:\t"  +  msg
            )
    }
    */

    $jq.getJSON(url, function(data) {
        func(flattencart(data)) 
    })
}



//----- D I S P L A Y   F U N C T I O N S -----//

// match original foxycart html 
function  fcCartView(cart) {

    var head = ' \
               <div id="fc_cart_container"> \
               <div id="fc_cart_container_inner"> \
               <noscript> \
               <div id="fc_error_noscript" class="fc_error"> \
               <h3>Warning:</h3> \
               <p>Our checkout process requires javascript. Please <a href="http://www.foxycart.com/index.php?id=28" target="_blank">click here to enable javascript</a>. You may then click the checkout button below, or refresh this page to make changes to your cart.</p> \
               </div><!-- #fc_errorNoScript --> \
               </noscript> \
               <form id="fc_cart_form" action="/cart.php" method="post" name="fc_cart_form"> \
               <div id="fc_cart_controls_top"> \
               <input type="hidden" name="cart" value="update" /> <a class="fc_link_nav fc_cart_update" href="#" onclick="fc_UpdateCart();return false;">Update Cart</a> <a class="fc_link_nav fc_link_forward fc_cart_checkout" href="/v/0.5.0/checkout.php?ThisAction=customer_info&amp;PHPSESSID=ksulc51fhtf72dh2g3nbh2qas1" target="_top">Checkout</a> <span class="fc_cart_notice c1">Please update your cart.</span> \
               </div><!-- #fc_cart_controls_top --> \
               <table id="fc_cart_table" cellspacing="0" cellpadding="0"> \
               <caption>Your Cart</caption> \
               <thead> \
               <tr id="fc_cart_head"> \
               <th id="fc_cart_head_item"><span>Item</span></th> \
               <th id="fc_cart_head_edit"><span>Edit</span></th> \
               <th id="fc_cart_head_price"><span>Price</span></th> \
               </tr> \
               </thead> \
               ';
                
                
    var totals = ' \
                 <tfoot> \
                 <tr id="fc_cart_foot_subtotal"> \
                 <td class="fc_col1" colspan="2">Subtotal:</td> \
                 <td class="fc_col2">$' + cart['total_price'] + '</td> \
                 </tr> \
                 <tr id="fc_cart_foot_total"> \
                 <td class="fc_col1" colspan="2">Order Total:</td> \
                 <td class="fc_col2">$' + cart['total_price'] + '</td> \
                 </tr> \
                 </tfoot> \
                 ';




    var items = ''
    
    for (var k in cart['products']) {
//        alert(typeof cart['products'][k]["discount"]);
        items += ' \
                 <tr class="fc_cart_item" id="' + cart['products'][k]["reg id"] + '"> \
                 <td>' + cart['products'][k]["name"] + ' \
                 <ul class="fc_cart_item_options">'

        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Code</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["code"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Category</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["category"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Start Date</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["start date"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Student Name</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["student first name"] + ' ' + cart['products'][k]["student last name"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Student Age</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["student age"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Original Price</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["original price"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Resident</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["resident"] + '</span></li>'
        items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Member</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["member"] + '</span></li>'

        if( typeof cart['products'][k]["discount"] !== 'undefined' ) {
            items += '<li class="fc_cart_item_option"><span class="fc_cart_item_option_name">Discount</span><span class="fc_cart_item_option_separator">:</span> <span class="fc_cart_item_option_value">' + cart['products'][k]["discount"] + '</span></li>'
        }


        items += ' \
                 <td class="fc_cart_item_edit"> \
                 <span class="fc_cart_remove_center">' + cart['products'][k]["x"] + '</span> \
                 </td>'
                 
        items += ' \
                 <td class="fc_cart_item_price"> \
                 <span class="fc_cart_item_price_total">$' + cart['products'][k]["price"] + '</span> \
                 </td>'

        items += '</tr>'
    }

    


 
 
    var foot = ' \
               </table> \
               <div id="fc_cart_controls_bottom"> \
               <input type="hidden" name="cart" value="update" /> <input type="hidden" name="item_count" value="3" /> <input type="hidden" name="PHPSESSID" value="ksulc51fhtf72dh2g3nbh2qas1" /> <a class="fc_link_nav fc_cart_update" href="#" onclick="fc_UpdateCart();return false;">Update Cart</a> <a class="fc_link_nav fc_link_forward fc_cart_checkout" href="/v/0.5.0/checkout.php?ThisAction=customer_info&amp;PHPSESSID=ksulc51fhtf72dh2g3nbh2qas1" target="_top">Checkout</a> <span class="fc_cart_notice c1">Please update your cart.</span> \
               </div><!-- #fc_cart_controls_bottom --> \
               </form> \
               </div> \
               </div><!-- #fc_cart_container_inner, #fc_cart_container --> \
               <!-- end cart output --> \
               ';



return head + totals + items + foot

}



//----- D E B U G  &  H E L P E R   F U N C T I O N S -----//

// P R I N T _ R
// html 
function  pr(X) {
    var o = '<TABLE border=1>'

    for (var k in X) {
        if(typeof(X[k]) == 'object') {
            o += '<tr><th>' + k + '<td>' + pr(X[k])
        } else {
            o += '<tr><th>' + k + '<td>' + X[k]
        }
    }

return o + '</TABLE>'

}

// js alert
function  pra(X) {
    var o = '\n'

    for (var k in X) {
        if(typeof(X[k]) == 'object') {
            o += k + ': ' + pra(X[k]) + '\n'
        } else {
            o += k + ': ' + X[k] + '\n'
        }
    }

return o + '\n'

}



//----- O L D  or  U N U S E D -----//

////   C L E A R
//function  clear()
//{ generic( 'http://mmadev.foxycart.com/cart?cart=empty' ) }


////   S E N D    I T E M
//function  senditem(item) {
//    var url = 'https://mmadev.foxycart.com/cart' + getstr(item)
//    generic( url )
//}


////   R E M O V E    I T E M
//function  removeitems() 
//{ generic( 'http://mmadev.foxycart.com/cart?cart=update&1:quantity=0&1:id=686013' ) }


////   A D D    I T E M
//function  additem(obj) {
//    var obj = getstr( obj )
//    generic( 'http://mmadev.foxycart.com/cart?x:yada=one'  +  obj )
//}


////    S U B M I T
//function  submitthis() {
//  
//    senditem( r2j() )
//    
//return false
//    
//}


//function  discovery(){
//    id('category').value = 'discovery'
//    submitthis( id ( 'discovery' ) )
//}


//function  defaultcat(){
//    id('category').value = 'default'
//    submitthis( id ( 'discovery' ) )
//}


//   V I E W
//function  discview(cart) { 
//    
//    var inn = filterin( cart['products'] )
//    var out = filterout( cart['products'] )
//    var disc = discount( cart['products'] )
//    inn.sort(comp)
//            
//    id('quick').innerHTML = encodeproducts(disc)
//
//    id('in').innerHTML        = pr( inn )
//    id('out').innerHTML        = pr( out )
//    id('disc').innerHTML    = pr( disc )
//    id('cart').innerHTML    = pr( cart )
//    
//}














