var empty            = /^\s*$/;
var RecaptchaOptions = {theme : 'custom'};
var $j               = jQuery.noConflict();
var cart             = new Cart();
var g_productColumns = ['shelf_number', 'product_number', 'quantity', 'cost'];
var g_arrProducts    = {};

$j(document).ready(function(){
    disableSubmitsOnClick();

    $j("#ProductMakeId").bind("change", getModels);
    $j("#ProductMakeId2").bind("change", {no:"2"}, getModels);
    $j("#ProductMakeId3").bind("change", {no:"3"}, getModels);
    $j("#ProductMakeId4").bind("change", {no:"4"}, getModels);

    $j("#ProductMakeName").bind("change", getModelsByMakeName);
    $j("#UserCompanyId").bind("change", selectUserGroup);

	$j.preloadImages(
		g_img_url + "img/collapse.png",
		g_img_url + "img/menu_selected.png",
		g_img_url + "img/pass.png",
		g_img_url + "img/fail.png",
        g_img_url + "img/autodom_home/bumper_h.jpg",
        g_img_url + "img/autodom_home/distributor_h.jpg",
        g_img_url + "img/autodom_home/headlight_h.jpg",
        g_img_url + "img/autodom_home/hood.jpg",
        g_img_url + "img/autodom_home/radiator.jpg",
        g_img_url + "img/autodom_home/strut-assembly.jpg"
	);
});

function selectUserGroup(){
    var companyID = $j("#UserCompanyId").val();
    if(!empty.test(companyID)){
        $j.ajax({
            type: "POST",
            url: g_webroot+"companies/ajax_getUserGroup/"+companyID,
            success: function(data){
                var selectedIndex = 0;
                $j("#UserUserGroupId").find("option").each(function(i){
                    if( $j(this).val() == data ){
                        document.getElementById("UserUserGroupId").options.selectedIndex=selectedIndex;
                    }
                    selectedIndex++;
                });
            }
        });
    }
}

function getModels(event){
	var no = "";

	if( typeof event.data != "undefined" )
        no = event.data.no;

    $j("#ProductModelId"+no).removeOption(/./);
    selectBox = document.getElementById("ProductMakeId"+no);
    makeID = selectBox.options[selectBox.selectedIndex].value;
    $j.ajax({
        type: "POST",
        url: g_webroot+"models/ajax_getModels/"+makeID,
        async: false,
        success: function(data){
            if( !empty.test(data) && data != "false" ){
                data = JSON.parse(data);
                $j( "#ProductModelId"+no ).addOption(data, false);
            }   
        }
    });
}

function getModelsByMakeName(){
    var modelBox = $j("#ProductModelName")[0];
    if(typeof modelBox == "undefined") return;
    $j("#ProductModelName").removeOption(/./);
    selectBox = document.getElementById("ProductMakeName");
    makeName = selectBox.options[selectBox.selectedIndex].value;
    $j.ajax({
        type: "POST",
        url: g_webroot+"models/ajax_getModelsByMakeName/"+encodeURIComponent(makeName),
        async: false,
        success: function(data){
            if( !empty.test(data) && data != "false" ){
                data = JSON.parse(data);
                $j( "#ProductModelName" ).addOption(data, false);
            }   
        }
    });
}

function deleteFile(fileID){
    $j.ajax({
        type: "POST",
        url: g_webroot+"files/ajax_delete/"+fileID,
        success: function(data){
            if(data != 0) $j("#File_"+fileID).remove();
            else alert(__("Failed to delete file"));
        }
    });
}

function __(str){
    return str;
}

function disableSubmitsOnClick(height,width,extraStyle){
    var style = '';

    if( typeof height == "undefined" ) height = "";
    else height = "height:"+height+"px";

    if( typeof width == "undefined" ) width = "";
    else width = "width:"+width+"px";

    if( typeof extraStyle == "undefined" ) extraStyle = "";

    if( !empty.test(height) && !empty.test(width) ){
        style = "style='"+height+";"+width+";"+extraStyle+"'";
    }
    $j(':submit,:image').unbind("click");
	$j(':submit,:image').bind("click", function(e){
        if($j(this).is(":visible"))
            $j(this).css("display", "none").after("<input class='disabledButton' "+style+" type='button' disabled='disabled' value='processing..'/>");
	});
}

function signup_checkUsernameAvailability(){
	if( empty.test($j("#UserSignupUsername").val()) ){
		return false;
	}
	
	$j.ajax({
		type: "POST",
		url: g_webroot + "users/ajax_checkUsernameAvailability/",	
		data: "data="+JSON.stringify({"username":$j("#UserSignupUsername").val()}),
		success: function(data){
			if( data == 1 ){
				displayError($j("#UserSignupUsername"), __("Username is already taken. Please select a different username."));
			} else {
				displayError($j("#UserSignupUsername"));
			}
		}
	});
}

function signup_checkEmailAvailability(){
	if( empty.test($j("#UserEmail").val()) ){
		return false;
	}
	
	$j.ajax({
		type: "POST",
		url: g_webroot + "users/ajax_checkEmailAvailability/",	
		data: "data="+JSON.stringify({"email":$j("#UserEmail").val()}),
		success: function(data){
			if( data == 1 ){
				displayError($j("#UserEmail"), __("Email is already taken. Please select a different email."));
			} else {
				displayError($j("#UserEmail"));
			}
		}
	});
}

/**
 *displays an error under an element.
 */
function displayError(element, msg){
    if(typeof msg=="undefined") msg = "";
    var parent = $j( element ).parent();

    if( empty.test(msg) ){
        $j( parent ).children("#error").remove();
    } else {
        $j( parent ).children("#error").remove();
        $j( parent ).append( "<div id='error'>"+msg+"</div>");
        $j( element ).focus();
    }   
}

/**
 *outlines an element if it has error
 */
function hasError(element){
    //for some reason chaning field class didn't have
    //any effect so i had to do this
    element.addClass("input_error");
}

/**
* removes the red outline
*/
function clearError(element){
    element.removeClass("input_error");
}

function removeThickBoxEvents() {
    $j('.thickbox').each(function(i) {
        $j(this).unbind('click');
    });
}

var g_timerCalled = false;

function Cart(){
    this.items = [];
    this.total = 0.0;

    this.timerUpdate = function(process, elementID){
        if(typeof process == "undefined") process = false;
        if(!process) {
            if( !g_timerCalled ){
                g_timerCalled = true;
                setTimeout('cart.timerUpdate(true, "'+elementID+'");', 1000); 
            }
        } else {
            g_timerCalled = false;
            var items = [];
            $j('.'+elementID+'-qty').each(function(i){
                var id_String = $j(this).attr('id');
                var id_Array = id_String.split('-');
                var id = id_Array[4];
                var qty = $j(this).val();
                items.push({"id":id, "qty":qty});
            });
            if(items.length>0){
                $j.ajax({
                    cart: this,
                    type: "POST",
                    url: g_webroot+"shopping_cart/ajax_updateCartQuantities",
                    data: "data="+JSON.stringify(items),
                    success: function(data){
                        cart.update();
                        cart.updateCheckout();
                    }
                });
            }
        }
    }

    this.toggleContent = function(){
        $j('#basket').toggle();
        if($j('#basket').is(':visible') && $j('#basket-content').html() == '')
            this.updateContent();
    }

    this.updateContent = function(){
        $j('#basket-content').load(g_webroot+"shopping_cart/ajax_getCartItems/html");
    }

    this.addItem = function(productID, qty){
        if(typeof qty == "undefined") qty = 1;
        if(!empty.test(qty)) this.addToPhpCart(productID, qty);
    }

    this.updateCheckout = function(){
        $j('#checkout-content').load(g_webroot+"shopping_cart/ajax_getCheckoutItems/");
    }

    this.update = function(updateContent){
        if(typeof updateContent == "undefined") updateContent = true;
        $j.ajax({
            cart: this,
            type: "POST",
            url: g_webroot+"shopping_cart/ajax_getTotals/",
            success: function(data){
                if(empty.test(data)) return;
                data = JSON.parse(data);
                $j("#cart-items").html(data.numberOfItems);
                $j("#cart-totals").html(data.totalPrice);
                if(updateContent) cart.updateContent(); 
            }
        });
    }

    this.addToPhpCart = function(productID, qty){
        var ret = true;
        $j.ajax({
            cart: this,
            type: "POST",
            url: g_webroot+"shopping_cart/ajax_addToCart/"+productID+"/"+qty,
            success: function(data){
				if(data=="INSUFFICIENT_PRODUCT"){
					alert("Sorry! we do not have enough of this product. Please reduce the quantity");
				} else {
					ret = data==1?true:false;
					cart.items[productID] = new CartItem(productID, qty);
					cart.items[productID].updateMessage(__("Added to cart"));
					cart.update();
				}
            }
        });
        return ret;
    }

    this.removeItem = function(productID){ 
        if(confirm(__("Are you sure you want to remove this item from your cart?"))){
            $j.ajax({
                cart: this,
                type: "POST",
                url: g_webroot+"shopping_cart/ajax_removeItem/"+productID,
                success: function(data){
                    ret = data==1?true:false;
                    if(ret){
                        delete cart.items[productID];
                        cart.update();
                        cart.updateCheckout();
                    } else {
                        alert(__("Due to a system error the item could not be removed. Please try again later"));
                    }
                }
            });
        }
    }

    this.clear = function(){ 
        if(confirm(__("Are you sure you want to clear the basket"))){
            $j.ajax({
                cart: this,
                type: "POST",
                url: g_webroot+"shopping_cart/ajax_clear",
                success: function(data){
                    ret = data==1?true:false;
                    if(ret){
                        cart.items = [];
                        cart.update();
                    } else {
                        alert(__("Due to a system error cart content could not be clear. Please try again later"));
                    }
                }
            });
        }
    }
}

function CartItem(productID, qty){
    this.product = null;
    this.qty = parseFloat(qty);
    this.productID = productID;

    this.getQty = function(){
        return parseFloat(this.qty);
    }

    this.updateMessage = function(msg, type){
        if(typeof type == "undefined") type = "success";
        $j("#product-"+this.productID+"-message").css("display","block");
        $j("#product-"+this.productID+"-message").removeClass();
        $j("#product-"+this.productID+"-message").addClass("cart-product-message-"+type);
        $j("#product-"+this.productID+"-message").html(msg);
        $j("#product-"+this.productID+"-message").fadeOut(3000);
    }
}

CartItem.prototype.loadItem = function(){
    $j.ajax({
        itemInstance: this,
        type:       "POST",
        url:        g_webroot+"products/ajax_getProduct/"+this.productID,
        async:      false,
        success:    function(data){
            if(data==0) return alert(__("Error: Product could not added to cart. Please try again later."));
            else {
                if(empty.test(data)) return;
                data = JSON.parse(data);
                this.itemInstance.product = data;
                this.itemInstance.productID = this.itemInstance.product['Product']['id'];
            }
        }
    });
}

function order_expandItem(orderID){
    if($j("#order-lines-"+orderID).is(":visible")){
        $j("#order-lines-"+orderID).hide();
        $j("#expand-links-"+orderID).html("<img src='"+g_img_url+"img/expand.png' border='0' alt='Expand' title='Expand'/>");
    } else {
        $j("#order-lines-"+orderID).show();
        $j("#expand-links-"+orderID).html("<img src='"+g_img_url+"img/collapse.png' border='0' alt='Collapse' title='Collapse'/>");
    }
}

function updatePrice(){
    tb_show("update price", "./#TB_inline?height=180&width=300&inlineId=newPrice");
}

var g_partsIncludedHtml = "";

function getPartsIncluded(productTypeID){
    var loadParts = true;

    //if parts already loaded we save the html so we can put it back in
    if( typeof g_partsLoaded != "undefined" && g_partsLoaded === true ){
        //put back
        if(productTypeID == g_productTypeID){
            loadParts = false;
            $j("#partsIncludedPlaceHolder").html(g_partsIncludedHtml);
        } else {
            //if save
            loadParts = true;
            if(empty(g_partsIncludedHtml)) g_partsIncludedHtml = $j("#partsIncludedPlaceHolder").html();
        }
    } 

    if(loadParts)
        $j.ajax({
            type: 'POST',
            url: g_webroot+"products/ajax_getPartsIncluded/"+productTypeID,
            success: function(data){
                if(data !== 0){
                    var html = '';
                    if(empty.test(data)) return;
                    data = JSON.parse(data);
                    for(var part in data){
                        html += "<li>"
                        html += "<input type='checkbox' name='data[Product][parts_included]["+data[part]+"]' /> " + data[part];
                        html += "</li>";
                    }
                    $j("#partsIncludedPlaceHolder ul").html(html);
                }
            }
        });
}

function alertUserNotification(){
	alert("Customer will be notified if shipment is changed.")
}

$j.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		$j("<img>").attr("src", arguments[i]);
	}   
}   

function productsApplyToSelected(){
    $j(".defaultUserGroup").each(function(i){
        var userGroupID = $j(this).attr("id").split("_")[1];
        var margin      = $j("#"+userGroupID+"_defaultMargin").val();
        var price       = $j("#"+userGroupID+"_defaultPrice").val();

        if( price != 0 && price != "" ){
            $j(".productRows").each(function(i){
                var productID  = $j(this).attr("id").split("_")[0];
                if( $j("#productCheckbox_"+productID).attr("checked")==true){
                    priceObj  = $j("#"+productID+"-"+userGroupID+"_price");
                    priceObj.val(price);
                    calculateMargin(productID, $j("#"+productID+"-"+userGroupID+"_price"), userGroupID);
                }
            });
        } else if( margin != 0 && margin != "" ){
            $j(".productRows").each(function(i){
                var productID  = $j(this).attr("id").split("_")[0];
                if( $j("#productCheckbox_"+productID).attr("checked")==true){
                    marginObj = $j("#"+productID+"-"+userGroupID+"_margin");
                    marginObj.val(margin);
                    calculatePrice(productID, $j("#"+productID+"-"+userGroupID+"_margin"), userGroupID);
                }
            });
        }
    });
}

/**
 * After the default price/margin is set this function
 * applies those default values to all result set rows
 * 
 * @return void
 * @author Hamid
 */
function productsApplyToAll(){
    $j(".defaultUserGroup").each(function(i){
        var userGroupID = $j(this).attr("id").split("_")[1];
        var margin      = $j("#"+userGroupID+"_defaultMargin").val();
        var price       = $j("#"+userGroupID+"_defaultPrice").val();

        if( price != 0 && price != "" ){
            $j(".productRows").each(function(i){
                var productID  = $j(this).attr("id").split("_")[0];
                priceObj  = $j("#"+productID+"-"+userGroupID+"_price");
                priceObj.val(price);
                calculateMargin(productID, $j("#"+productID+"-"+userGroupID+"_price"), userGroupID);
            });
        } else if( margin != 0 && margin != "" ){
            $j(".productRows").each(function(i){
                var productID  = $j(this).attr("id").split("_")[0];
                marginObj = $j("#"+productID+"-"+userGroupID+"_margin");
                marginObj.val(margin);
                calculatePrice(productID, $j("#"+productID+"-"+userGroupID+"_margin"), userGroupID);
            });
        }
    });
}

function productsCheckAll(){
    $j(".productCheckboxes").each(function(i){
        $j(this).attr('checked', true);
    });
}

function productsCheckNone(){
    $j(".productCheckboxes").each(function(i){
        $j(this).attr('checked', false);
    });
}

function productsCheckToggle(){
    var i  = 0;
    $j(".productCheckboxes").each(function(i){
        if( $j(this).attr('checked') == true ){
            $j(this).attr('checked', false);
        } else {
            $j(this).attr('checked', true);
        }
    });
}

/**
 * given a product id it will go and fetch all the fields and stores the values
 * into a global array to be saved later on
 * 
 * @param productID 
 * @return void
 * @author Hamid
 */
function addProductToArray(productID){
    var rowHash    = $j("#"+productID+"_hash").val();
    var arrTmp     = {};
    var hashString = "";

    for(var column in g_productColumns){
        var col     = g_productColumns[column];
        var id      = "#"+productID+"_"+g_productColumns[column];
        var val     = $j(id).val();
        arrTmp[col] = val;

        hashString += val;
    }

    //get user group info
    arrTmp['user_groups_margins'] = {};
    $j('.'+productID+'_userGroupPrice').each(function(i){
        userGroupID = $j(this).attr('id').split("_")[0].split("-")[1];

        marginObj = $j("#"+productID+"-"+userGroupID+"_margin");
        priceObj  = $j("#"+productID+"-"+userGroupID+"_price");

        arrTmp['user_groups_margins'][userGroupID] = {"price":priceObj.val(), "margin":marginObj.val()};

        hashString += marginObj.val();
        hashString += priceObj.val();
    });

    //get new hash to see if values has changed
    var hash = hex_md5(hashString);

    //only save the values if the values have changed
    if(rowHash != hash) {
        g_arrProducts[productID] = arrTmp;
        $j("#btnProductsSAve").attr("disabled",true);
    }
}

/**
 * Checks if the global array has values in it then
 * it will try to save it
 * 
 * @return void
 * @author Hamid
 */
function saveGlobalProductArray(){
    if(countJson(g_arrProducts) > 0){
        $j.ajax({
            type    : "POST",
            url     : g_webroot+"products/ajax_saveProductsArray/",
            data    : 'data='+JSON.stringify(g_arrProducts),
            success : function(data){
                data = JSON.parse(data);
                //if product row has failed to save display the fail icon
                for(var id in data.fail){
                    productID = data.fail[id];
                    updateProductStatus(productID, "fail");
                }

                //if data has been saved properly then show the pass icon
                for(var id in data.pass){
                    productID = data.pass[id];
                    calculateHash(productID);
                    updateProductStatus(productID, "pass");
                }

                //reset
                g_arrProducts = {};
                $j("#btnProductsSave").attr("disabled", false);
            }
        });
    }
}

/**
 * Loops through all rows of the product in a search result
 * and checks if the values are changed then it will collect
 * them into a global array and save them at the end. If the hash
 * of the values were not changed the row will not be saved.
 * 
 * @access public
 * @return void
 * @author Hamid
 */
function productsSave(){
    j=0;
    $j(".productRows").each(function(i){
        var productID  = $j(this).attr("id").split("_")[0];
        addProductToArray(productID);
    });
    saveGlobalProductArray();
}

/**
 * Calculates md5 hash of the values of a row of product; this is used
 * to determine if the value of the row is changed or not
 * 
 * @param productID 
 * @return void
 * @author Hamid
 */
function calculateHash(productID){
    var hashString = "";
    for(var column in g_productColumns){
        var col     = g_productColumns[column];
        var id      = "#"+productID+"_"+g_productColumns[column];
        var val     = $j(id).val();
        hashString += val;
    }

	$j('.'+productID+'_userGroupPrice').each(function(i){
		userGroupID = $j(this).attr('id').split("_")[0].split("-")[1];
		marginObj   = $j("#"+productID+"-"+userGroupID+"_margin");
		priceObj    = $j("#"+productID+"-"+userGroupID+"_price");
		hashString += marginObj.val();
		hashString += priceObj.val();
	});
    hash = hex_md5(hashString);
    $j("#"+productID+"_hash").val(hash);
}

/**
 * Show success or failure image for each row of the product
 * 
 * @param productID 
 * @param status 
 * @return void
 * @author Hamid
 */
function updateProductStatus(productID, status){
    $j("#"+productID+"_saveStatus").html("<img src='"+g_img_url+"img/"+status+".png' alt='Failed to save' title='Failed to Save'/>");
    $j("#"+productID+"_saveStatus").slideDown();
}

/**
 * Calculate price of a product based on its cost and margin
 * 
 * @param productID 
 *      Database id of the product
 * @param focusedObj 
 *      Object that the user is currently focused.  
 * @param userGroupID 
 *      The user group id the user is on
 * @return void
 * @author Hamid
 */
function calculatePrice(productID, focusedObj, userGroupID){
    if(productID) var costObj = $j("#"+productID+"_cost");
    else var costObj = $j("#ProductCost");
    var focusedObj = $j(focusedObj);
    var cost       = costObj.val();

	//if groupID is not given it means the user is updating the cost
	if( !userGroupID ){
        if(productID){
            $j("."+productID+"_userGroupPrice").each(function(i){
                userGroupID = $j(this).attr('id').split("_")[0].split("-")[1];
                calculatePrice(productID, focusedObj, userGroupID);
            });
        } else {
            $j(".userGroupPrice").each(function(i){
                userGroupID = $j(this).attr('id').split("_")[0];
                calculatePrice(null, focusedObj, userGroupID);
            });
        }
	} else {
		//if group id is given then we update the price for that group
        if(productID){
            marginObj = $j("#"+productID+"-"+userGroupID+"_margin");
            priceObj  = $j("#"+productID+"-"+userGroupID+"_price");
            margin    = marginObj.val().replace(/%/, "");
        } else {
            marginObj = $j("#"+userGroupID+"_margin");
            priceObj  = $j("#"+userGroupID+"_price");
            margin    = marginObj.val().replace(/%/, "");
        }

		if( !empty.test(cost) && cost != "0" && 
			!empty.test(margin) && margin != "0" &&
			priceObj.attr("id") != focusedObj.attr("id") ){

			cost          = parseFloat(cost);
			marginPercent = parseFloat(margin/100);
			finalPrice    = parseFloat(cost + (cost * marginPercent));
			priceObj.val( roundVal(finalPrice,0) );
		}
	}
}

function calculateMargin(productID, focusedObj, userGroupID){
    if( productID ) var costObj = $j("#"+productID+"_cost");
    else var costObj = $j("#ProductCost");
    var focusedObj = $j(focusedObj);
    var cost       = costObj.val();

	//if groupID is not given it means the user is updating the cost
	if( !userGroupID ){
        if(productID){
            $j("."+productID+"_userGroupPrice").each(function(i){
                userGroupID = $j(this).attr('id').split("_")[0].split("-")[1];
                calculateMargin(productID, focusedObj, userGroupID);
            });
        } else {
            $j(".userGroupPrice").each(function(i){
                userGroupID = $j(this).attr('id').split("_")[0];
                calculateMargin(null, focusedObj, userGroupID);
            });
        }
	} else {
		//if group id is given then we update the price for that group
        if(productID){
            marginObj = $j("#"+productID+"-"+userGroupID+"_margin");
            priceObj  = $j("#"+productID+"-"+userGroupID+"_price");
            price     = priceObj.val().replace(/[$,]/, "");
        } else {
            marginObj = $j("#"+userGroupID+"_margin");
            priceObj  = $j("#"+userGroupID+"_price");
            price     = priceObj.val().replace(/[$,]/, "");
        }

		if( !empty.test(cost) && cost != "0" && 
			!empty.test(price) && price != "0" &&
			marginObj.attr("id") != focusedObj.attr("id") ){

			cost         = parseFloat(cost);
			finalMargin  = ((price - cost)/cost)*100
			marginObj.val( roundVal(finalMargin,0) );
		}
	}
}

function showUserGroups(){
    $j("#toggleUserGroupHandle").html("wait...");
    $j(".product_userGroupRow").show(0,function(){
       $j("#toggleUserGroupHandle").html("Hide User Groups");
    });
}
function hideUserGroups(){
    $j("#toggleUserGroupHandle").html("wait...");
    $j(".product_userGroupRow").hide(0, function(){
        $j("#toggleUserGroupHandle").html("Show User Groups");
    });
}

function toggleStoreCreditCod(){
	if($j("input[name='data[Company][account_type]']:checked").val() == "STORE_CREDIT")
		$j("#company_store_credit").slideDown();
	else
		$j("#company_store_credit").slideUp();

}
