var _ajaxUrl = _base_lang + "/mtdental_ajax.php";

/*
	Tyco Login JAVASCRIPT settings and functions
	Author: Eytan Chen
	Published: January 2008
	all rights reserved to Tyco Interactive ltd.
	http://www.tyco.co.il
*/

function checkLogin(cForm)
{
	if (cForm.userName.value == "" || cForm.password.value == "")
	{
		alert(_login_userandpass);
		if(cForm.userName.value == "")
			cForm.userName.focus();
		else if(cForm.password.value == "")
			cForm.password.focus();
	}
	else
	{
		// ajax check login
		var url = "tyco_login.ajax.php?logMember=true&userName="+cForm.userName.value+"&password="+cForm.password.value+"&cstType="+cForm.cstType.value;
		var xml = LoadXML(url);
		if(xml != null)
		{
			if (xml.getElementsByTagName('login')[0].firstChild.data == "logged"){
				location.reload();
			}
			else
			{
				var message = xml.getElementsByTagName('rsp')[0].firstChild.data;
				alert (message);
				cForm.userName.focus();
			}
		}
	}
	return false;
}


function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else
	{
		window.onload = function()
		{
			if (oldonload) oldonload();
			func();
		}
	}
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain )
{
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// this function gets the cookie, if it exists
function Get_Cookie( name )
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function checkPhone(str)
{
	rePhoneNumber = new RegExp(/^[0-9]{0,3}\s?\-?\s?[0-9]{7,10}$/);
	if (!rePhoneNumber.test(str))
		return false;

	return true;

}
function checkEmail(str) {
///// function for validating email address
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1){
		    return false
		} else if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		    return false
		} else 	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		} else  if (str.indexOf(at,(lat+1))!=-1){
		    return false
		} else 	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false
		} else  if (str.indexOf(dot,(lat+2))==-1){
		    return false
		} else if (str.indexOf(" ")!=-1){
		     return false
		} else {
 		 	return true
 		}
}

function getFlashMovieObject(movieName)
{
	if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName];
	if (window.document[movieName])
		return window.document[movieName];
	if (navigator.appName.indexOf("Microsoft Internet")==1)
		return document.getElementById(movieName);
}



function getHTTPObject()
{
	try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {}
	try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}
	try {return new XMLHttpRequest();} catch(e) {}
	alert("XMLHttpRequest not supported");
	return null;
 }

function LoadHTML(url)
{

	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  {return;}
		   var serverResponse = xmlHttp.responseText;

	}
	xmlHttp.send(null);
	return xmlHttp.responseText;
}
function LoadXML(url)
{
	var xmlHttp = getHTTPObject();
	xmlHttp.open("GET",url, false);
	xmlHttp.onreadystatechange = function()
	{
		   if (xmlHttp.readyState != 4)  {return;}
		   var serverResponse = xmlHttp.responseText;
	};
	xmlHttp.send(null);
	return xmlHttp.responseXML.documentElement;
}

function PostXML(url,params)
{
	xmlHttp = false;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest && !(window.ActiveXObject))
	{
		try {
			xmlHttp = new XMLHttpRequest();
		} catch(e) {
			xmlHttp = false;
		}
		// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject)
	{
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xmlHttp = false;
			}
		}
	}

	if (xmlHttp)
	{
		xmlHttp.open( "POST", url, false );
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
		return xmlHttp.responseXML.documentElement;
	}
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.-, ";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 }

function trim(strText) {
/// TRIM STRING FUNCTION
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);
    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);
   return strText;
}

function escapeString(sString)
{
// DETECT WHAT TO PUT STRING IN FOR HTML FORM ( ' OR " ) DEPANDING ON STRING CONTENTS
	if (sString.indexOf("'") == -1)
		valSep = "'";
	else
		valSep = '"';
	return valSep+sString+valSep;
}

function replaceSubstring(inputString, fromString, toString) {
 // GOES THROUGH THE INPUTSTRING AND REPLACES EVERY OCCURRENCE OF FROMSTRING WITH TOSTRING
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) {tempMidString += midStrings[i];}
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
}

function popupWin(popUrl, width, height)
{
	if (!navigator.appName.indexOf("Microsoft")) width+=20;
	height+=5;
	topVar=((screen.height / 2)-(height/2));
	leftVar=((screen.width / 2)-(width/2));
	window.open(popUrl, "PopUp", "height="+height+", width="+width+", top="+topVar+", left="+leftVar+", scrollbars=yes, status=no, location=no, resize=yes, menubar=no, titlebar=no, toolbar=no");
}

function focusField(f, def)
{
	if (f.value == def) f.value = "";
}

function blurField(f, def)
{
	f.value = trim(f.value);
	if (f.value == "") f.value = def;
}

function getFileExtension(filename)
{
	if( filename.length == 0 ) return "";
	var dot = filename.lastIndexOf(".");
	if( dot == -1 ) return "";
	var extension = filename.substr(dot,filename.length);
	return extension
}

function fix_external_links() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");

	var basicPattern = new RegExp('^(http:\/\/|https:\/\/)');
	var pattern = new RegExp('^(http:\/\/|https:\/\/)'+location.hostname);

	for (var i = 0; i < anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("rel") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
		else if (getFileExtension(anchor.href) == ".pdf") {
			anchor.target = "_blank";
		}
		else if (!anchor.href.match(basicPattern))  // this is for links such as "javascript" or "#" which do not include http or https at all !!
			continue;
		else if (!anchor.href.match(pattern) && !anchor.getAttribute("rel") || (anchor.getAttribute("rel") && anchor.getAttribute("rel") != "ibox")) {
			anchor.target = "_blank";
		}
	}
}

var Pagination = {
    curPage : 0,
    totalPages : 0,

    init : function(total) {
        this.totalPages = total;
        $("#pagination-next").click(function() {
            Pagination.showNext();
        });

        $("#pagination-prev").click(function() {
            Pagination.showPrev();
        });

        $("#pagination-area a").not("#pagination-next,#pagination-prev").click(function() {
            Pagination.curPage = parseInt($(this).html()) - 1;
            Pagination.showPage();
        });

        this.setMinHeight();
        this.highlight();
    },

    setMinHeight : function() {
        var maxHeight = 0;
        for (var i=0; i<this.totalPages; i++) {
            maxHeight = Math.max($("#page_" + i).height(), maxHeight);
        }

        for (var i=0; i<this.totalPages; i++) {
            $("#page_" + i).css("min-height", maxHeight);
        }
    },

    showPage : function() {
        $(".pagination-page").hide();
        $("#page_" + this.curPage).show();
        this.highlight();
    },

    highlight : function() {
        $("#pagination-text-area").html(sTpl.showPage + (this.curPage + 1) + sTpl.from + this.totalPages + sTpl.totalPages);
        $("#pagination-area a").removeClass("active");
        $("#pagination-area a").not("#pagination-next,#pagination-prev").each(function() {
            if (parseInt($(this).html()) == Pagination.curPage + 1) {
                $(this).addClass("active");
                return;
            }
        });
    },

    showNext : function() {
        if (this.curPage >= this.totalPages-1)
            return;

        this.curPage ++;
        this.showPage();
    },

    showPrev : function() {
        if (this.curPage == 0)
            return;

        this.curPage --;
        this.showPage();
    }

}


var TablePagination = {
    curPage : 0,
    totalPages : 0,
    totalItems : 0,
    linesPerPage : 0,
    tbl : null,
    pageSel : null,
    nextBtn : null,
    prevBtn : null,
    sep : null,

    init : function(tblId, npageId, nextId, prevId, sepId) {
        this.tbl = $("#" + tblId);
        this.pageSel = $("#" + npageId);
        this.nextBtn = $("#" + nextId);
        this.prevBtn = $("#" + prevId);
        this.sep = $("#" + sepId);

        this.totalItems = this.tbl.find("tr").not(".header").length;
        this.calcTotalPages();
        this.pageSel.bind("change", function() {
            TablePagination.pageSelectionChanged();
        });

        this.nextBtn.click(function() {
            TablePagination.nextPage();
        });

        this.prevBtn.click(function() {
            TablePagination.prevPage();
        });

        this.render();
    },

    calcTotalPages : function() {
        this.linesPerPage = parseInt(this.pageSel.val());
        if (this.linesPerPage == 0)
            this.linesPerPage = 1;

        this.totalPages = Math.ceil(this.totalItems / this.linesPerPage);
    },

    pageSelectionChanged : function() {
        this.calcTotalPages();
        this.curPage = 0;
        this.render();
    },

    nextPage : function() {
        if (this.curPage < this.totalPages - 1) {
            this.curPage ++;
            this.render();
        }
    },

    prevPage : function() {
        if (this.curPage > 0) {
            this.curPage --;
            this.render();
        }
    },

    renderButtons : function() {
        var hasNext;
        var hasPrev;

        if (this.curPage < this.totalPages - 1) {
            hasNext = true;
            this.nextBtn.show();
        }
        else {
            hasNext = false;
            this.nextBtn.hide();
        }

        if (this.curPage > 0) {
            hasPrev = true;
            this.prevBtn.show();
        }
        else {
            hasPrev = false;
            this.prevBtn.hide();
        }

        if (hasNext && hasPrev) {
            this.sep.show();
        }
        else {
            this.sep.hide();
        }
    },

    render : function() {
        this.renderButtons();
        var offsetStart = this.curPage * this.linesPerPage;
        var offsetEnd = (this.curPage + 1) * this.linesPerPage;
        if (offsetEnd > this.totalItems)
            offsetEnd = this.totalItems;

        var elm = this.tbl.find("tr").not(".header");
        
        for (var i=0; i<this.totalItems; i++) {
            if (i >= offsetStart && i < offsetEnd) {
                $(elm[i]).show();
            }
            else {
                $(elm[i]).hide();
            }
        }
    }
}



var ContactForm = {
    $subElm : null,

    init : function() {
        this.$subElm = $("#send-btn");
        this.$subElm.click(function() {
            ContactForm.submit();
        });

        $("#clear-btn").click(function() {
            $("#contact-form input").val("");
        });
    },

    collectData : function() {
        var obj = {
            firstName : $("#first-name").val(),
            lastName : $("#last-name").val(),
            phone : $("#phone").val(),
            email : $("#email").val(),
            subject : $("#subject").val(),
            type : $("#type").val(),
            content : $("#text-content").val(),
            joinMailing : $("#join-mailing").is(":checked")
        };

        return obj;
    },

    submit : function() {
        this.showMessage("");
        var obj = this.collectData();
        obj.action = "addContact";
        //this.hideMessage();
        this.hideButtons();
        $.post(_ajaxUrl, obj, function(data) {
            ContactForm.processResponse(data);
        });
    },

    processResponse : function(obj) {
        obj = $.evalJSON($.base64Decode(obj));
        if (obj.status != true) {
            this.showMessage(obj.errorMsg);
            this.showButtons();
        }
        else {
            $("#contact-form-data,#contact-form").hide();
            this.showConfirmation(obj.confMsg);
        }
    },

    showMessage : function(msg) {
        $("#form-message span:first").html(msg);
        $("#form-message").show();
    },

    hideMessage : function() {
        $("#form-message").hide();
    },

    hideButtons : function() {
        $("#send-btn,#clear-btn").hide();
    },

    showButtons : function() {
        $("#send-btn,#clear-btn").show();
    },

    showConfirmation : function(msg) {
        $("#form-message span:first").html(msg);
        $("#form-message img").hide();
        $("#form-message").show();
    }
}

var JoinMailing = {
    init : function() {
        $("#joinml-method").bind("change", function() {
            JoinMailing.selectionChanged($(this).val());
        });

        $("#joinml-send").click(function() {
            JoinMailing.submitForm();
        });
    },

    submitForm : function() {
        this.resetErrors();
        var method = parseInt($("#joinml-method").val());
        //validate
        var phoneRq = false;
        var emailRq = false;
        switch (method) {
            case 1:
                phoneRq = true;
                break;

            case 2:
                emailRq = true;
                break;

            default:
                phoneRq = true;
                emailRq = true;
                break;
        }

        //check name
        var name = $("#joinml-name").val();
        if (name.length == 0) {
            $("#joinml-name").addClass("error-border");
            alert(_errors.badName);
            return;
        }

        var phone = $("#joinml-phone").val();
        var email = $("#joinml-email").val();
        if (phoneRq && phone.length == 0) {
            $("#joinml-phone").addClass("error-border");
            alert(_errors.badPhone);
            return;
        }

        if (emailRq && !checkEmail(email)) {
            $("#joinml-email").addClass("error-border");
            alert(_errors.badEmail);
            return;
        }

        var obj = {
            action : "joinMailing",
            name : name,
            email : email,
            phone : phone,
            method : method
        };

        $.post(_ajaxUrl, obj, function(data) {
            obj = $.evalJSON($.base64Decode(data));
            if (obj.status == true) {
                alert(_errors.mlSuccess);
            }
            else {
                alert(_errors.mlError);
            }
        });
    },

    resetErrors : function() {
        $("#joinml-email,#joinml-phone,#joinml-name").removeClass("error-border");
    },

    selectionChanged : function(val) {
        this.resetErrors();
        val = parseInt(val);
        switch (val) {
            case 1:
                $("#joinml-phone-cnt").show();
                $("#joinml-email-cnt").hide();
                $("#joinml-email").val("");
                break;

            case 2:
                $("#joinml-email-cnt").show();
                $("#joinml-phone-cnt").hide();
                $("#joinml-phone").val("");
                break;

            default:
                $("#joinml-phone-cnt").show();
                $("#joinml-email-cnt").show();
                break;
        }
    }
}

var SalesBox = {
    total : 0,
    cur : 0,
    init : function(total) {
        this.total = total;
        if (total < 2)
            return;

        setTimeout(function() {
            SalesBox.render();
        }, 4000);
    },

    render : function() {        
        var next = this.cur + 1;
        if (next == this.total)
            next = 0;
        
        $("#sale-image" + this.cur + ",#sale-text" + this.cur).fadeOut("normal");
        $("#sale-image" + next +",#sale-text" + next).fadeIn("normal");
        
        this.cur = next;
        //timeout
        setTimeout(function() {
            SalesBox.render();
        }, 4000);
    }
}

function initSearch() {
    $("#search-term").val(sTpl.search);

    $("#search-term").focus(function() {
        var val = $(this).val();
        if (val == sTpl.search) {
            $(this).val("");
        }
    })
    .blur(function() {
        var val = $(this).val();
        if (val.length == 0)
            $(this).val(sTpl.search);
    });

    $("#search-btn").click(function() {
        doSearch();
    });
}

function doSearch() {
    var term = $("#search-term").val();
    if (term.length == 0 || term == sTpl.search) {
        alert(sTpl.searchError);
        return;
    }

    $("#search-form").submit();
}

function initFooter() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    if (is_chrome) {
        //strange chrome offset behaviour
        $("#footer").css("position", "fixed").css("bottom", "0px");
        $("#footer-padding").css("padding-top", 20);
    }
    else {
        $("#footer-padding").css("padding-top", 0);
        fixFooterPosition();
        $(window).resize(function() {
            $("#footer-padding").css("padding-top", 0);
            fixFooterPosition();
        });
    }
}

function fixFooterPosition() {
    var $footer = $("#footer");
    var winHeight = $(window).height();
    var footerPosition = $footer.offset().top;
    if (footerPosition >= winHeight)
        //leave at that
        return;

    var padding = winHeight - footerPosition - $footer.height() - 32;
    $("#footer-padding").css("padding-top", padding);
}



function submitRegister(f)
{
	// disable submit button and change its class
	submitButton = document.getElementById("submitForm");
	submitButton.disabled = true;

	ReqFields = new Array("userName","password","confirm","fullName","birthDay","companyName","companyAddress","supplyAddress","role","phone","fax","email","agree");
	for (i=0;i<ReqFields.length; i++)
	{	
		fieldName = ReqFields[i];
		if (trim(f[fieldName].value) == "")
		{		
			cMessage = eval("_"+fieldName);
			alert(cMessage);
			f[fieldName].focus();
			submitButton.disabled = false;
			return false;
		}

		if (fieldName == "email" && !checkEmail(f[fieldName].value))
		{
			alert(_emailInvalid);
			f[fieldName].focus();
			submitButton.disabled = false;
			return false;
		}

		if (fieldName == "phone" && !checkPhone(f[fieldName].value))
		{
			alert(_phoneInvalid);
			f[fieldName].focus();
			submitButton.disabled = false;
			return false;
		}
		
		if (fieldName == "fax" && !checkPhone(f[fieldName].value))
		{
			alert(_faxInvalid);
			f[fieldName].focus();
			submitButton.disabled = false;
			return false;
		}

	}
	
	 if ( f['password'].value != f['confirm'].value )
	 {
	 		alert(_password_confirm);
			f['password'].focus();
			submitButton.disabled = false;
			return false;
	 }
	 
	  if ( !f['agree'].checked )
	 {
	 		alert(_agree);
			f['agree'].focus();
			submitButton.disabled = false;
			return false;
	 }

	if (confirm(_register_confirm))
	{
		advAJAX.submit(f, {
		    onSuccess : function(obj) {
		    		if (obj.responseText != "")
		    		{
		    			alert (_register_success);
		    			f.reset();
		    			submitButton.disabled = false;
		    		}    		
		    		else
		    		{
		    			alert (_register_fail);
		    			submitButton.disabled = false;
		    		}
		    }
		});
		return false;
	}

	submitButton.disabled = false;
	return false;
}



function targetAndOpenMenu(link)
{
	setTimeout("window.location.href='"+link+"'", 800);
}

function addToCart(prdid)
{
	var url = _base+"/cart_ajax.php?id="+prdid;
	var xml = LoadHTML(url);
	if(xml == null)
	{
		alert(_itemadderror);
	}
	window.location.href=_base_lang+"/cart.php";//+_shopcartfrnd+".html";
	return false;
}

function checkpass(curForm)
{
	if(curForm.reminderEmail.value=="")
	{
		alert(_alert_email);
		curForm.reminderEmail.focus();
		return false;
	}
	if (!checkEmail(curForm.reminderEmail.value))
	{
		alert(_tpl_emailNotValid);
		curForm.reminderEmail.focus();

		return false;
	}
}


