// shared.js by Engin Kinali

var online = 0; // 1 = online, 0 = ej online
var errormessages = new Array();
var firsttime=0;


// Funktion som visar felmeddelanden i en meddelanderuta

function showErrors() {

    if( errormessages.length > 0 ) {

        mes = "Följande fel inträffade:<BR><BR>";

        for( i = 0; i < errormessages.length; i++ ) {

            mes += (i+1) + ": " + errormessages[i] + "<BR>";

        }

        alert( mes );

        errormessages = new Array();

    }

}



// Funktion som visar felmeddelanden i DIV eller SPAN elementet  på sidan vars id skickas som argument till funktionen

function printErrors( elementname ) {

    if( errormessages.length > 0 ) {

        mes = "<SPAN CLASS=label>F&ouml;ljande fel intr&auml;ffade:</SPAN><BR><BR>";

        for( i = 0; i < errormessages.length; i++ ) {

            mes += "<SPAN CLASS=label>" + (i+1) + ":</SPAN> " + errormessages[i] + "<BR>";

        }

        mes += "<BR>";

        updateElement( elementname, mes );

        errormessages = new Array();

    }

}



function showAlertMessage( message ) {

    alert( message );

}



// Används vid utveckling. Meddelandevisningen bör stängas av online genom att sätta variabeln online till 1

function showErrorReport( errorObject, message ) {

    mes = "Fel i programkoden.\n";

    mes += message + "\n";



    if( errorObject.constructor != undefined ) mes += "errorObject.constructor: " + errorObject.constructor + "\n";

    if( errorObject.name != undefined ) mes += "errorObject.name: " + errorObject.name + "\n";

    if( errorObject.number != undefined ) mes += "errorObject.number: " + errorObject.number + "\n";

    if( errorObject.message != undefined ) mes += "errorObject.message: " + errorObject.message + "\n";

    if( errorObject.filename != undefined ) mes += "errorObject.filename: " + errorObject.filename + "\n";

    if( errorObject.lineNumber != undefined ) mes += "errorObject.lineNumber: " + errorObject.lineNumber + "\n";

    if( errorObject.description != undefined ) mes += "errorObject.description: " + errorObject.description + "\n";



    if( online != 1 ) showAlertMessage( mes );

}



function changeImage( path, picelementname, picname ) {

    if( document.images ) {

        document.images[picelementname].src = path + picname;

    }

}



// Konverterar kommatecken i theValue till punkter och returnerar det nya värdet

function convertCommasToDots( theValue ) {

    theValue = theValue.replace( ",", "." ); return theValue;

}



// Kontrollerar om det angivna värdet är ett giltigt tal (decimaltal är giltiga)

function validateNumber( theValue ) {

    theValue = convertCommasToDots( theValue ); return !isNaN( theValue );

}



// Kontrollerar om det angivna värdet är ett heltal

function validateInteger( theValue ) {

    return /^-?\d+$/.test( theValue );

}

// Alias för checkInteger

function validateInteger( theValue ) {

    return checkInteger( theValue );

}



// Kontrollerar om den angivna strängen endast består av bokstäver, siffror, tecknet _ och tecknen . och -

function detectForbiddenChars( str ) {

    return /^[\w\.\-]+$/.test( str );

}



// Kontrollerar om den angivna e-post adressen är en giltig e-post adress

function validateEmail(email) {

    return /^[\w\.\-]+@[\w\.\-]+\.\w{2,}$/.test( email );

}



// Kontrollerar om det angivna datumet är ett giltigt datum i formatet ÅÅÅÅ-MM-DD

function validateDate( datestr ) {

    re = /^\d\d\d\d-\d\d-\d\d$/; return re.test( datestr );

}



// Kontrollerar om det angivna datumet är ett giltigt datum i formatet ÅÅ-MM-DD

function validateDate2( datestr ) {

    re = /^d\d-\d\d-\d\d$/; return re.test( datestr );

}



// Kontrollerar om det angivna klockslaget �r ett giltigt klockslag i formatet TT_MM:SS

function validateTime( timestr ) {

    re = /^\d\d:\d\d:\d\d$/; return re.test( timestr );

}



function getTodaysDate() {

    var mydate=new Date();

    var year=mydate.getYear();

    if( year < 2000 ) year=1900+year;

    var day=mydate.getDay()

    var month=mydate.getMonth()



    if ( month < 10 ) {

        fullmonth = "0" + ( month + 1 );

    }



    if ( day < 10 ) {

        fullday = "0" + day;

    }

    return today = ( year + "-" + ( fullmonth ) + "-" + fullday );

}



function validateBirthdate( birthdate ) {

    today = getTodaysDate();



    var errors = new Array();

    thisyear = today.substr( 0, 4 );

    thismonth = today.substr( 5, 2 );

    thisday = today.substr( 8, 2 );



    if( !checkDate( birthdate ) ) {

        errors.push( "Födelsedatumet är inte giltigt." );

    }

    else {

        year = birthdate.substr( 0, 4 );

        month = birthdate.substr( 5, 2 );

        day = birthdate.substr( 8, 2 );

        if( year > thisyear || year < "1900" ) {

            errors.push( "År kan inte vara tidigare än 1900." );

        }

        if( Math.round( month ) > 12 || Math.round( month ) < 1 ) {

            errors.push( "Månad kan inte vara mindre än 1 och större än 12." );

        }

        if( Math.round( day ) > 31 || Math.round( day ) < 1 ) {

            errors.push( "Dag kan inte vara mindre än 1 och större än 31." );

        }



        //      alert( "year=" + year + " thisyear=" + thisyear + "\n" + "month=" + Math.round( month ) + " thismonth=" + Math.round( thismonth ) + "\n" +

        //				"day=" + Math.round( day ) + " thisday=" + Math.round( thisday ) );



        if( errors.length == 0 ) {

            if(

                ( ( thisyear - year ) < 18 ) ||

                ( ( thisyear - year ) < 18 && ( Math.round( month ) > Math.round( thismonth ) ) ) ||

                ( ( thisyear - year ) < 18 && ( Math.round( month ) >= Math.round( thismonth ) ) && ( Math.round( day ) > Math.round( thisday ) ) )

                ) {

                errors.push( "Du måste ha fyllt 18 är för att kunna använda denna site." );

            }

        }



    }



    if( errors.length > 0 ) {

        returnvalue = "";

        for( i = 0; i < errors.length; i++ ) {

            returnvalue += errors[i] + "\n";

        }

        return returnvalue;

    }

    return true;

}



// Kontrollerar om det angivna v�rdet �r ett heltal

function validateInteger( theValue ) { return /^-?\d+$/.test( theValue ); }



function validatePersnr( persnr ) { re = /^\d\d\d\d\d\d-\d\d\d\d$/; return re.test( persnr ); }



// Slut : Olika funktioner för att validera inmatade v�rden



// Funktion som &ouml;ppnar ett nytt f&ouml;nster med angiven url och angiven bredd+50, angiven h&ouml;jd+50

function openwin( url, width, height ) {

    width += 50; height += 50;

    if( ( width > screen.availWidth ) ) {

        width = screen.availWidth;

    }

    if( ( height > screen.availHeight ) ) {

        height = screen.availHeight;

    }

    y = (screen.availHeight / 2) - (height / 2); x = (screen.availWidth / 2) - (width / 2);

    if( window.popup_window && !window.popup_window.closed ) {

        window.popup_window.close();

    }

    popup_window = window.open(url,'','width='+width+',height='+height+',resizable=yes,menubar=no,' + 'scrollbars=yes,status=no,toolbar=no,screenX='+x+',screenY='+'y'+',left='+x+',top='+y);

    popup_window.focus();

}



function changePic( picname, newpictablename ) {

    if( picname != selectedpicname ) {

        picnamesrc = document.images[picname].src;

        if( path == "" ) {

            path = picnamesrc.substr( 0, picnamesrc.lastIndexOf( "/" ) + 1 );

        }

        newpictablenamesrc = path + newpictablename;

        if( document.images ) {

            document.images[picname].src = newpictablenamesrc;

        }

    }

}



function refreshShopbagframe( urlpath ) { top.right.location = urlpath + "right.php"; top.bottom.location = urlpath + "bottom.php"; }



var popup_window = "";



function openwin( url, width, height ) {

	width += 50; height += 50;

	if( ( width > screen.availWidth ) ) { width = screen.availWidth; }

	y = (screen.availHeight / 2) - (height / 2); x = (screen.availWidth / 2) - (width / 2);

	if( window.popup_window && !window.popup_window.closed ) { window.popup_window.close(); }

	popup_window = window.open(url,'','width='+width+',height='+height+',resizable=yes,menubar=no,' + 'scrollbars=yes,status=no,toolbar=no,screenX='+x+',screenY='+'y'+',left='+x+',top='+y);

	popup_window.focus();

}



function popupwin(url) {

    width = 650; height = 670;

	if( ( width > screen.availWidth ) ) { width = screen.availWidth; }

	y = ( screen.availHeight / 2 ) - ( height / 2 ); x = ( screen.availWidth / 2 ) - ( width / 2);

	if( window.popup_window && !window.popup_window.closed ) {

		window.popup_window.moveTo( x, y );

		window.popup_window.resizeTo( width+20, height+30 );

	}

	var window_specs = "location=no, scrollbars=yes, menubar=yes, toolbars=no,resizable=yes," +

		"left=" + x + ",top=" + y + ",width=" + width + ",height=" + height;

	popup_window = window.open( url, '', window_specs );

	popup_window.focus();

}



function setKredittyp( typ ) {

	 document.avbetalningsform.kredittyp.value=typ;

}



// Funktion som anpassar f�nstrets storlek till uppl�sningen 1024X728. Anv�nds vid utvecklingen av webbplatsen

function customizeWindowSize( winwidth, winheight) {

	if( winwidth == 0 || winheight == 0 ) {

		winwidth = 1024; winheight = 768;

	}

	if(window.screen) {

		winwidth=1024; winheight=768;

		if(  ( screen.availWidth >= winwidth || screen.availHeight >= winheight ) ) {

			top.resizeTo( winwidth, winheight ); top.moveTo( ( screen.availWidth/2 )-winwidth/2, (screen.availHeight/2)-winheight/2 );

		}

		else { top.resizeTo( screen.availWidth, screen.availHeight ); top.moveTo( 0, 0 ); }

	}

}



function showSearchresult( typ, depth ) {

	searchword = document.searchform.searchword.value;

	if( searchword.length < 2 ) {

		alert( "S�kordet m�ste best� av minst 2 tecken." );

		if( typ == 1 ) return false;

	}

	else {

		top.main.location.replace( depth + "basicsearcher.php?searchword=" + searchword );

		if( typ == 1 ) return true;

	}

}

function clearSearchField() {

	if( document.searchform.searchword.value == "S�k efter produkt" ) {

		document.searchform.searchword.value = "";

	}

}



// Sp�ra kolli

function searchConsignment(url) {

	winwidth = 800;

	winheight = 600;

	y = (screen.availHeight / 2) - (winheight / 2 );

	x = (screen.availWidth / 2) - (winwidth / 2);

	window.open(url,"");

}



function strtrim() {

	return this.replace(/^\s+/,'').replace(/\s+$/,'');

}



String.prototype.trim = strtrim;



function removeTextAndSubmit(){

	if (document.trackForm.consignmentId.value.trim() == "Ditt kolli/brev id" || 

		document.trackForm.consignmentId.value.trim() == "") {

		document.trackForm.trackntraceAction.value = "";

		document.trackForm.consignmentId.value = "";

		document.trackForm.IntLinkNOCATEGORYCName.value = "tracktrace.remotecontrol.searchnotdone";

	} else {

		document.trackForm.IntLinkNOCATEGORYCName.value = "tracktrace.remotecontrol.searchdone";

	}

	consignmentId = document.trackForm.consignmentId.value;

	IntLinkNOCATEGORYCName = document.trackForm.IntLinkNOCATEGORYCName.value;

	trackntraceAction = document.trackForm.trackntraceAction.value;

	url = "http://www.posten.se/tracktrace/TrackConsignments_do.jsp?" + 

			"consignmentId=" + consignmentId + "&IntLinkNOCATEGORYCName=" + IntLinkNOCATEGORYCName +

			"&trackntraceAction=" + trackntraceAction;

	searchConsignment( url );

// 	document.trackForm.submit();

}



function changeContent() {

	document.trackForm.consignmentId.value = "";

}



function removeSlTextAndSubmit() {

	newValue = document.slForm.REQ0JourneyStopsS0G.value.trim();

	document.slForm.REQ0JourneyStopsS0G.value = newValue;

	document.slForm.submit();

}

// Slut p� Sp�ra kolli







// Funktion som skapar ett REQUEST objekt

function createRequest() {

	var newrequest = null;

	try {

		newrequest = new XMLHttpRequest();

	}

	catch (trymicrosoft) {

		try {

			newrequest = new ActiveXObject("Msxml2.XMLHTTP");

		}

		catch (othermicrosoft) {

			try {

				newrequest = new ActiveXObject("Microsoft.XMLHTTP");

			}

			catch (failed) {

				newrequest = null;

			}

		}

	}

	if ( newrequest == null) { alert("Ett fel upsptod p� sidan.\nVissa funktioner kanske inte fungerar som det ska." ); }

	return newrequest;

}



function emptyElement( elementname ) {

	if( $( elementname ) != undefined && $( elementname ) != null ) Element.update( elementname, "" );

}



function updateElement( elementname, text ) {

	if( $( elementname ) != undefined && $( elementname ) != null ) Element.update( elementname, text );

}



function removeElement( elementname ) {

	if( $( elementname ) != undefined && $( elementname ) != null ) Element.remove( elementname );

}



// Gör det angivna elementet synligt om det är dolt och vice versa. elementname är id:t till vilket element som helst på sidan

function hide_showElement( elementname ) {

    try {

        $( elementname ).visible() == true ? $( elementname ).hide() : $( elementname ).show();

    }

    catch( e ) {

        message = "Feltyp:" + e.name + "\nMöjlig orsak: Elementet \"" + elementname + "\" existerar inte eller har fel typ." +

        "\nDetta felmeddelande kommer från funktionen \"hide_showElement()\" i filen \"shared.js\"";

        showErrorReport( e, message );

    }

}



function isVisible( elementname ) {

    returnvalue = false;

    if( $( elementname ) && $( elementname ).visible() ) {

        returnvalue = true;

    }

    else {

        returnvalue = false;

    }

    return returnvalue;

}



function hideElement( elementname ) {

    try {

        $( elementname ).hide();

    }

    catch( e ) {

        message = "Feltyp:" + e.name + "\nMöjlig orsak: Elementet \"" + elementname + "\" existerar inte eller har fel typ." +

        "\nDetta felmeddelande kommer från funktionen \"hideElement()\" i filen \"shared.js\"";

        showErrorReport( e, message );

    }

}



function showElement( elementname ) {

    try {

        $( elementname ).show();

    }

    catch( e ) {

        message = "Feltyp:" + e.name + "\nMöjlig orsak: Elementet \"" + elementname + "\" existerar inte eller har fel typ." +

        "\nDetta felmeddelande kommer från funktionen \"showElement()\" i filen \"shared.js\"";

        showErrorReport( e, message );

    }

}



// Funktion som laddar valfri fil i valfritt SPAN el. DIV element av sidan

// Visar inget meddelande utan ersätter först innehållet i elementname med loading bilden och laddar sedan innehållet och ersätter loading bilden.

function getPage( requestobj, filnamn, messagespot, elementname, paramurl, loadingpictype ) {

	loadingpicwidth = 16; loadingpicheight = 16;

	loadingpicpathandname = "pics/smallloading.gif";

	if( loadingpictype == 1 ) {

		loadingpicpathandname = "pics/bigloading.gif";

		loadingpicwidth = 48; loadingpicheight = 48;

	}

    //  showAlertMessage( paramurl );

    var url = filnamn + "?" + paramurl + "&dummy=" + new Date().getTime();

    element = document.getElementById( elementname );

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function showFile() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var getpageresponse = requestobj.responseText;

				if( $( elementname ) )

	                updateElement( elementname, getpageresponse );

				if( $( messagespot ) )

					emptyElement( messagespot );

            }

        }

        else {

			if( loadingpictype == 1 ) {

				if( $( elementname ) )

					updateElement( elementname,

							"<DIV STYLE=\"text-align:center;\"><IMG SRC=" + loadingpicpathandname + " WIDTH=" + loadingpicwidth + " HEIGHT=" + loadingpicheight + " BORDER=0></DIV>" );

			}

			else {

				if( $( messagespot ) )

					updateElement( messagespot,

							"<DIV STYLE=\"text-align:center;\"><IMG SRC=" + loadingpicpathandname + " WIDTH=" + loadingpicwidth + " HEIGHT=" + loadingpicheight + " BORDER=0> Laddar...</DIV>" );

			}

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



// Funktion som laddar valfri fil i valfritt SPAN el. DIV element av sidan

// Visar inget meddelande utan ersätter först innehållet i elementname med loading bilden och laddar sedan innehållet och ersätter loading bilden.

function getPage2( requestobj, filnamn, elementname, paramurl, loadingpictype ) {

	loadingpicwidth = 16; loadingpicheight = 16;

	loadingpicpathandname = "pics/smallloading.gif";

	if( loadingpictype == 1 ) {

		loadingpicpathandname = "pics/bigloading.gif";

		loadingpicwidth = 48; loadingpicheight = 48;

	}

    //  showAlertMessage( paramurl );

    var url = filnamn + "?" + paramurl + "&dummy=" + new Date().getTime();

    element = document.getElementById( elementname );

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function showFile() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var getpageresponse = requestobj.responseText;

                updateElement( elementname, getpageresponse );

            }

        }

        else {

            updateElement( elementname,

						"<DIV STYLE=\"text-align:center;\"><IMG SRC=" + loadingpicpathandname + " WIDTH=" + loadingpicwidth + " HEIGHT=" + loadingpicheight + " BORDER=0></DIV>" );

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



// Funktion som laddar valfri fil i valfritt SPAN el. DIV element av sidan

function getPage3( requestobj, filnamn, messageelementname, elementname, paramurl, loadingpicpathandname, loadingmessage ) {

    //  showAlertMessage( paramurl );

    loadingmessage = loadingmessage == "" ? "Laddar... Var god v&auml;nta..." : loadingmessage;

    var url = filnamn + "?" + paramurl + "&dummy=" + new Date().getTime();

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function showFile() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var getpageresponse = requestobj.responseText;

                emptyElement( elementname );

                updateElement( elementname, getpageresponse );

                emptyElement( messageelementname );

            }

            else {

        //                updateElement( messageelementname, "There was an error during loading the file " + filnamn + ".\nErrorcode: " + requestobj.status );

        }

        }

        else {

            updateElement( messageelementname,

                "<IMG SRC=" + loadingpicpathandname + " WIDTH=16 HEIGHT=16 BORDER=0 ALIGN=ABSMIDDLE> " + loadingmessage );

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



// Funktion som laddar valfri fil i valfritt SPAN el. DIV element av sidan

function getPage4( requestobj, filnamn, messageelementname, elementname, paramurl ) {

    //  showAlertMessage( paramurl );

    var url = filnamn + "?" + paramurl + "&dummy=" + new Date().getTime();

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function showFile() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var getpageresponse = requestobj.responseText;

                updateElement( elementname, getpageresponse );

                emptyElement( messageelementname );

            }

            else {

        //                updateElement( messageelementname, "There was an error during loading the file " + filnamn + ".\nErrorcode: " + requestobj.status );

            }

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



function getBody(data) { var argument = "value="; argument += encodeURIComponent(data) ; return argument; }



function ajaxSearch() {

    searchword = $F( "searchword" );

//    alert( "ajaxsearch.php" );

    if( searchword != "Sök efter produkt" ) {

	if( searchword.length > 1 ) {

	    getPage( createRequest(), "ajaxsearch.php", "mainmessagespot", "maincontentspot", "searchword=" + searchword + "&dummy=" + new Date().getTime() );

	}

	else {

//	    emptyElement( "maincontentspot" );

	}

    }

}



// Start menyfunktioner



var selectedmainsubdirdiv = ""; var selectedsubdirdiv = "";



function showSubdirDiv( divid, headdirid ) {

    if( $( divid ) ) {

        subdirdiv = "dynamic_" + divid;

        if( $( selectedsubdirdiv ) && subdirdiv == selectedsubdirdiv ) {

            hide_showElement( selectedsubdirdiv );

            selectedsubdirdiv = "";

        }

        else {

            if( $( subdirdiv ) ) {

                hide_showElement( subdirdiv );

            }

            else {

                contentparamurl = "h=" + headdirid;

//                alert( contentparamurl );

                getPage3( createRequest(), "mainpage.php", "mainmessagespot", "maincontentspot", contentparamurl, "images/smallloading.gif", "Laddar... Var god vänta" );

                paramurl = "divid=" + divid + "&headdirid=" + escape( headdirid );

                getPage4( createRequest(), "subdirlist.php", "menumessagespot", divid, paramurl );

            }

        }

        selectedmainsubdirdiv = divid; selectedsubdirdiv = "dynamic_" + divid;

    }

}



// Slut menyfunktioner



function higligtTabLabel( labelname ) {

    menulabels = new Array( "lblreadmore", "lbldosage", "lblcontent", "lblinfo", "lblrate" );

    for( i = 0; i < menulabels.length; i++ ) {

		if( $( menulabels[i] ) ) {

			$( menulabels[i] ).setStyle(

			{

				background: '#E4E4DA'

			}

			);

		}

    }

    for( i = 0; i < menulabels.length; i++ ) {

        if( menulabels[i] == labelname ) {

			if( $( menulabels[i] ) ) {

				$( menulabels[i] ).setStyle(

				{

					background: '#A2A2A2'

				}

				);

			}

        }

    }

}



// Visar den valda top5 listan. filetype bestämmer vilen lista som ska visas. 1= Top 5 jobb, 2= Top 5 företag, 3 = Top 5 Sökord

function showTab( filename, contentspot, prodid, filetype, labelname ) {

//	alert( labelname );

//    emptyElement( contentspot );

	paramurl = "prodid=" + prodid + "&filetype=" + filetype;

//	alert( paramurl );

	getPage2( createRequest(), filename, contentspot, paramurl, 1 );

    higligtTabLabel( labelname );

}



function collectOpinion() {

	prodid = $F( "prodid" );

	firstname = $F( "firstname" ).strip();

	lastname = $F( "lastname" ).strip();

	email = $F( "email" ).strip();

	grade = $F( "grade" );

	text = $F( "text" ).strip();

	paramurl = "prodid=" + prodid + "&firstname=" + escape( firstname ) +

		"&lastname=" + escape( lastname ) + "&email=" + escape( email ) + "&grade=" + grade + "&text=" + escape( text );



	messagespot = "prodmessagespot"; contentspot = "prodinfocontent";

	loadingpicwidth = 16; loadingpicheight = 16;

	loadingpicpathandname = "pics/smallloading.gif";

    //  showAlertMessage( paramurl );

    var url = "opinioncollecter.php?" + paramurl + "&dummy=" + new Date().getTime();



    requestobj = createRequest();

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function showFile() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var response = requestobj.responseText;

				if( response == 1 ) {

//					alert( response );

					updateElement( contentspot,

								  "<DIV CLASS=label STYLE=\"text-align:center;\">" +

								  "Tack f&ouml;r ditt omd&ouml;me!<BR><BR>" +

								  "Ditt omd&ouml;me kommer att bli synligt n&auml;r det har kontrollerats och godk&auml;nts av v&aring;ra administrat&ouml;rer.</DIV>" );

					emptyElement( messagespot );

				}

				else {

		            updateElement( messagespot, response );

				}

            }

        }

        else {

            updateElement( messagespot, "<IMG SRC=" + loadingpicpathandname + " WIDTH=" + loadingpicwidth + " HEIGHT=" + loadingpicheight + " BORDER=0>" );

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



function buy() {

	prodid = $( "prodid" ) ? $F( "prodid" ) : 0;

	color = $( "color" ) ? $F( "color" ).strip() : "";

	taste = $( "taste" ) ? $F( "taste" ).strip() : "";

	size = $( "size" ) ? $F( "size" ).strip() : "";

	design = $( "design" ) ? $F( "design" ).strip() : "";

	prodcount = $( "prodcount" ) ? $F( "prodcount" ).strip() : 0;

	if( !validateInteger( prodcount ) ) {

		alert( "Antal måste vara ett heltal!")

		$( "prodcount" ).select();

	}

	else {

		paramurl = "optype=1&prodid=" + prodid + "&color=" + escape( color ) + "&taste=" + escape( taste ) + "&size=" + escape( size ) + "&design=" + design +

			"&prodcount=" + escape( prodcount );

	//	alert( paramurl );

		var url = "shopbaghandler.php?" + paramurl + "&dummy=" + new Date().getTime();

	

		requestobj = createRequest();

		requestobj.open("POST", url, true);

		requestobj.onreadystatechange = function doYourThing() {

			if( requestobj.readyState == 4 ) {

				if( requestobj.status == 200 ) {

					emptyElement( "buyprocessspot" );

					var response = requestobj.responseText;

					if( response == 1 ) {

						if (firsttime==0) alert("Produkten har nu lagts till i din kundvagn uppe till höger");
						getPage4( createRequest(), "shopbag.php", "shopbagmessagediv", "shopbagdiv", "" );
					}

					else {

						alert( "Fel upppstod!\n" + response );

					}

				}

			}

			else {

				updateElement( "buyprocessspot", "<IMG SRC=pics/smallloading.gif WIDTH=16 HEIGHT=16 BORDER=0 ALIGN=ABSMIDDLE> L&auml;gger i kundvagnen..." );

			}

		}

		requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

		requestobj.send( paramurl );

	}

}



// Visar den stora kundvagnen

function showBigShopbag() {

	getPage2( createRequest(), "shopbagbig.php", "maincontentspot", "", 1 );

}



function updateShopbag( index ) {

	prodcount = $( "prodcount" + index ) ? $F( "prodcount" + index ).strip() : 0;

	if( !validateInteger( prodcount ) ) {

		alert( "Antal måste vara ett heltal!")

		$( "prodcount" + index ).select();

	}

	else {

		paramurl = "optype=3&index=" + index + "&prodcount=" + prodcount;

	//	alert( paramurl );

		var url = "shopbaghandler.php?" + paramurl + "&dummy=" + new Date().getTime();

	

		requestobj = createRequest();

		requestobj.open("POST", url, true);

		requestobj.onreadystatechange = function doYourThing() {

			if( requestobj.readyState == 4 ) {

				if( requestobj.status == 200 ) {

					var response = requestobj.responseText;

	//				alert( response );

					if( response == 1 ) {

						showBigShopbag();

//						getPage4( createRequest(), "shopbag.php", "shopbagmessagediv", "shopbagdiv", "" );

					}

					else {

	//					alert( "Fel upppstod!\n" + response );

					}

				}

			}

		}

		requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

		requestobj.send( paramurl );

	}

}



function removeFromShopbag( index ) {

	paramurl = "optype=2&index=" + index;

//	alert( paramurl );

    var url = "shopbaghandler.php?" + paramurl + "&dummy=" + new Date().getTime();



	requestobj = createRequest();

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function doYourThing() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var response = requestobj.responseText;

//				alert( response );

				if( response == 1 ) {

					showBigShopbag();

//					getPage4( createRequest(), "shopbag.php", "shopbagmessagediv", "shopbagdiv", "" );

				}

				else {

//					alert( "Fel upppstod!\n" + response );

				}

            }

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



// Visar den stora kundvagnen

function showDeskShopbag( messagespot, contentspot ) {

	if( $( "deskshopbagspot") ) {

		getPage( createRequest(), "shopbagdesk.php", messagespot, contentspot, "", 2 );

	}

}



function updateDeskShopbag( index, type ) {

	paramurl = "optype=4&index=" + index + "&type=" + type;

//	alert( paramurl );

	var url = "shopbaghandler.php?" + paramurl + "&dummy=" + new Date().getTime();



	updaterequestobj = createRequest();

	updaterequestobj.open("POST", url, true);

	updaterequestobj.onreadystatechange = function doYourThing() {

		if( updaterequestobj.readyState == 4 ) {

			if( updaterequestobj.status == 200 ) {

				var response = updaterequestobj.responseText;

				if( response == 1 ) {

					showDeskShopbag( "deskshopbagmessagespot", "deskshopbagspot" );

				}

				else {

					alert( "Fel upppstod!\n" + response );

				}

			}

		}

	}

	updaterequestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

	updaterequestobj.send( paramurl );

}



function removeFromDeskShopbag( index ) {

	paramurl = "optype=2&index=" + index;

//	alert( paramurl );

    var url = "shopbaghandler.php?" + paramurl + "&dummy=" + new Date().getTime();



	requestobj = createRequest();

    requestobj.open("POST", url, true);

    requestobj.onreadystatechange = function doYourThing() {

        if( requestobj.readyState == 4 ) {

            if( requestobj.status == 200 ) {

                var response = requestobj.responseText;

//				alert( response );

				if( response == 1 ) {

					showDeskShopbag( "deskshopbagmessagespot", "deskshopbagspot" );

				}

				else {

//					alert( "Fel upppstod!\n" + response );

				}

            }

        }

    }

    requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    requestobj.send( paramurl );

}



function adjustPayway( thevalue ) { // 0 = postförskott 1 = Förskottsbetalning 2 = Kortbetalning 3 = Faktura

	$( "payway" ).value = thevalue;

}



function adjustBuyrules() {

	if( $( "buyrules" ) ) {

		$( "buyrules" ).value = $( "chkbuyrules" ).checked ? 1 : 0;

	}

}



// Ta reda på om kundvagnen är tom

function getShopbagStatus() {

	if( !$( "shopbagstatus" ) ) {	// Om det finns något formelement på sidan som heter shopbagstatus dvs. om kundvagnen inte är tom

		return false;

	}

	return true;

}



// Skicka beställning

function sendOrder() {

	errors = new Array();

	if( getShopbagStatus() ) {

		firstname = $( "firstname" ) ? $F( "firstname" ) : "";

		lastname = $( "lastname" ) ? $F( "lastname" ).strip() : "";

		address = $( "address" ) ? $F( "address" ).strip() : "";

		zipcode = $( "zipcode" ) ? $F( "zipcode" ).strip() : "";

		city = $( "city" ) ? $F( "city" ).strip() : "";

		email = $( "email" ) ? $F( "email" ).strip() : "";

		tel = $( "tel" ) ? $F( "tel" ).strip() : "";

		comments = $( "comments" ) ? $F( "comments" ).strip() : "";

		ordertotalprice = $( "ordertotalprice" ) ? $F( "ordertotalprice" ).strip() : "";

		adjustBuyrules();

		payway = $( "payway" ) ? $F( "payway" ).strip() : "";

		buyrules = $( "buyrules" ) ? $F( "buyrules" ).strip() : 0;

		buyrules = $( "chkbuyrules" ).checked ? 1 : 0;



//		alert( payway );

		if( payway == "" ) { errors.push( "Du glömde att välja betalningssätt." ); }

		if( firstname == "" ) { errors.push( "Du glömde att ange ditt förnamn." ); }

		if( lastname == "" ) { errors.push( "Du glömde att ange ditt efternamn." ); }

		if( address == "" ) { errors.push( "Du glömde att ange din adress." ); }

		if( zipcode == "" ) { errors.push( "Du glömde att ange ditt postnummer." ); }

		if( city == "" ) { errors.push( "Du glömde att ange din stad." ); }

		if( email == "" ) { errors.push( "Du glömde att ange din e-post adress." ); }

		else {

		    if( !validateEmail( email ) ) {

			errors.push( "Du angav en ogiltig e-post adress.");

		    }

		}

//		if( tel == "" ) { errors.push( "Du glömde att ange ditt telefonnummer." ); }

//		if( mobil == "" ) { errors.push( "Du glömde att ange ditt mobilnummer." ); }

		if( buyrules == 0 ) { errors.push( "Du glömde att godkänna köpvillkoren." ); }

		if( validateInteger( payway ) && ( payway == "" || (payway.length)>1 ) )  { errors.push( "Du glömde att välja betalningssätt." ); }

		if( errors.length > 0 ) {

			mes = "Följande fel inträffade:\n\n";

			for( i = 0; i < errors.length; i++ ) {

				mes += (i+1) + " : " + errors[i] + "\n";

			}

			alert( mes );

		}

		else {

			paramurl = "firstname=" + escape( firstname ) + "&lastname=" +escape( lastname ) + "&address=" + escape( address ) +

							"&zipcode=" + escape( zipcode ) + "&city=" + escape( city ) +

							"&email=" + escape( email ) + "&tel=" + escape( tel ) + "&comments=" + escape( comments ) +

							"&buyrules=" + buyrules + "&payway=" + payway + "&ordertotalprice=" + ordertotalprice;

//			alert( paramurl );

			if( confirm("Detta kommer att skicka din beställning till Bodyvitamin. Vill du fortsätta?" ) ) {

				var url = "orderhandler.php?" + paramurl + "&dummy=" + new Date().getTime();

				requestobj = createRequest();

				requestobj.open( "POST", url, true);

				requestobj.onreadystatechange = function doYourThing() {

					if( requestobj.readyState == 4 ) {

						if( requestobj.status == 200 ) {

							var response = requestobj.responseText;

							// updateElement( deskmessagespot, response );

							if( response == 1 ) {

								// alert( response );

								if( payway != 2 ) {

									document.location="?p=12";

								}

								else {

//									document.location="redirect.php";

									document.location="http://www.bodyvitamin.se/redirect.php";

								}

								// updateElement( deskmessagespot, response );

							}

							else {

								updateElement( "deskmessagespot", response );

								alert( "Fel upppstod!\n" + response );

							}

						}

					}

				}

				requestobj.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

				requestobj.send( paramurl );

			}

		}

	}

}


