// JavaScript Document

function checkQtyMinMax (formInput,minQty, maxQty, currentProductOrderedAmount, fallBack, checkoutStage) {
	//set the qty from the input field
	var qty = parseFloat(formInput.value);

	// check the actual value of it to make sure it is a positive value and not a letter
	if(!isNaN(qty) && isFinite(qty) && qty>=0 && (qty % 1)==0){
		// only check maxQty if maxQty GT 0
		if (maxQty > 0) {
			// if its the check out stage it can be an update
			if (checkoutStage == 'true'){
				// qty < currentProductOrderedAmount OR qty <= maxQty it is an update to fewer products and is still <=
				if (qty < currentProductOrderedAmount || qty <= maxQty) {
					// set currentProductOrderAmount to 0
					currentProductOrderedAmount = 0
				}
			}

			// make sure they have not ordered more than the maximum quantity allowed
			if ((qty > maxQty) || ((qty+currentProductOrderedAmount) > maxQty)) {
				// additional message for variable set if they have already order the maximum
				if (currentProductOrderedAmount > 0) {
					additionalMessage = ' and you have already ordered ' + currentProductOrderedAmount ;
				} else {
					additionalMessage = '';
				}
				// set the fallback value and focus back on it
				formInput.value = fallBack;
				formInput.focus();

				// error message
				alert('The maximum order quantity is ' + maxQty + ' for this product' + additionalMessage + '.');
				return false;
			}

		}

		// only check minQty if minQty GT 0
		if (minQty > 0) {
			// make sure they have ordered more than the minimum quantity
			if (qty < minQty) {
				// set the default value and focus back on it
				formInput.value = minQty;
				formInput.focus();
				// tell them they must order a minimum
				alert('You must order a minimum quantity of ' + minQty + ' for this product.');
				return false;
			} 
		}

		// return true
		return true

	} else {
		formInput.value = fallBack;
		formInput.focus();
		alert('Please Enter a valid number. (no letters or negative values)');
		return false;
	}
}
	
var curmsg = 0;
var myText = new Array();
myText[0] = '<p>"I am so excited about AIM. I know that I enjoy teaching more now than ever before. You have helped me to reinvent myself as a teacher. It is an absolutely amazing approach to teaching French. Thank you so much!"</p><p class="citation">Darlene Bond, Core French Teacher, Toronto, ON</p>';
myText[1] = '<p>"I have been most excited by the way in which they write the creative stories after working on a play... The students\' knowledge, comfort and comprehension with the language they are using surpassed all my expectations. They are proud of themselves too! Thank you, thank you, thank you!"</p><p class="citation">Jennifer de Boer, Core French teacher, Saanichton, BC</p>';
myText[2] = '<p>"Parents were telling me that their children are practising the gestures at the dinner table, in the bathtub, in the car on the way home! ... I\'m especially pleased with my Special Ed classes. They\'re working at the same level as all the others!!! I\'m a happy, happy teacher!"</p><p class="citation">Emma Tilbury, Toronto, ON</p>';
myText[3] = '<p>"From an administrator\'s standpoint, I embrace the AIM program. Research tells us that students need to be actively involved in engaging material in order to make sense of and retain new material and AIM does just that!"</p><p class="citation">Aim Language Learning AIM - Parent &amp; Teacher Comments Testimonials &mdash; Linden Gray, Principal</p>';
myText[4] = '<p>"I am so thankful to have found such an effective method and would never teach any other way!"</p><p class="citation">Maryse West, Teacher</p>';
myText[5] = '<p>"I am thrilled with the success of this approach! I am using and will continue to use this approach and am grateful that someone like Wendy Maxwell has come along to change the future of French as a Second Language."</p><p class="citation">Ruta Nausedas</p>';
myText[6] = '<p>"This programme is absolutely revolutionary (you made me a "born again" French teacher, Wendy!) Thank you for another inspirational workshop!"</p><p class="citation">Shelley Zorzit</p>';
myText[7] = '<p>"J\'ai un grand enthousiasme pour ce projet, cette ann&eacute;e. &Ccedil;a me semble d\'&ecirc;tre un programme effectif et j\'ai h&acirc;te de voir les r&eacute;sultants. Merci beaucoup!"</p><p class="citation">Louise Cholette-Rees</p>';
myText[8] = '<p>"The gesture method is so effective, it\'s almost unbelievable. I used to stagger in with a big bin of props after hours of prep, and stand on my head trying to keep the kids focused. This is quick and easy, and I\'m very happy with the results thus far."</p><p class="citation">Debbie Soroczan, Ottawa</p>';
function slideMessage() {
	curmsg = Math.ceil((9*Math.random()) - 1);
	document.getElementById('quotes').innerHTML=myText[curmsg]; 
	setTimeout("slideMessage()",20000);
}

AC_FL_RunContent = 0;
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) 
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


YAHOO.util.Event.onDOMReady(slideMessage); 

/* SUCKERFISH*/
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


/* checkout form functions */
function check_required_fields() {
	$D = YAHOO.util.Dom;
        var el = $D.get('use_constant_contact');
        var toggle = false;
        if(el != null)
        {
            toggle = el.checked;
        }
	
	email = $D.get('billing_email').value;
	if(toggle && email==""){
		alert("please supply a billing email address for mailing list");
		return false;
	}
}


function check_alp(qty_el, min_qty, max_qty, current_order_amount, default_value, boolean_value, warehouse_id, part_num)
{
    //find out if we have a conflicting cart
    var conflict = is_conflict(warehouse_id, part_num);

    if(conflict == "You can only purchase one free trial!" ||
        conflict == "An Error has occured")
    {
        return false;
    }
    else if( (!conflict) || (conflict && confirm(conflict)) )
    {
        return checkQtyMinMax(qty_el, min_qty, max_qty, current_order_amount, default_value, boolean_value);
    }
    return false;
    //return checkQtyMinMax(qty_el, min_qty, max_qty, current_order_amount, default_value, boolean_value);
}

function is_conflict(wh_id, pn)
{
    var result = false;
    $.ajax(
        {
            url:    base_index_url + '/custom_controllers/alp_integration/cart_has_conflict',
            type:   'POST',
            data:   '&part_num=' + pn + '&warehouse_id=' + wh_id,
            async: false,
            success :function(a){
                try{
                    var data = jQuery.parseJSON(a);
                    if(data.free_trial_purchased != false)
                    {
                        //result = data.free_trial_purchased;
                        alert(data.free_trial_purchased);
                        result = "An Error has occured";
                        //result = false;
                    }
                    else if(data.has_conflict)
                    {
                        //var output = "The following items will be removed if you proceed with adding this item to your cart.\n\n";
			var output = "We are unable to process recurring and non-recurring products in the same shopping cart.\n";
			output += "Do you wish to add this item to your cart and remove the following products?\n\n";
                        //products will need to be removed
                        for(var i=0; i < data.to_remove.length; i++)
                        {
                            var prod = data.to_remove[i];
                            output +=  prod.warehouse.id + "-" + prod.part_num + " " + prod.description.short + ": x" + prod.quantity + "\n";
                        }
                        result = output;
                    }
                    else
                    {
                        result = false;
                    }
                }
                catch(e)
                {
                    result = "An Error has occured";
                    alert("An Error has occured");
                    //result = false;
                }
            },
            error: function(a)
            {
                result = false;
                return false;
            },
            failure: function(a)
            {
                result = false;
                return false;
            }
        }
    );
    return result;
}
