/*
 * Candam Jquery script plug-in for the web site
 *
 * http://www.candam.com/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 Philippe Menu
 *
 *
 */

/**
 * Several class definitions which will be used globally are located here.
 *
 */

// creating global instance for the global handler
   var Global;
   

   function listprodfeatures(prdid, test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductFeaturesWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductFeaturesWebJson";
        }
   
         $.ajax({type: "POST", async: false, contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'ProdID': "+prdid+"}", dataType: "json",
            success: function(feat) {
                       //alert(feat.d);
                       var first = true;
                       $("#feat ul").empty();
                       $(feat.d).each(function(){
                                 var pfid = this.ProductFeatureID;
                                 var fctnt = this.FeatureTextEn;
                                 if (!(this.ProductFeatureID == undefined)){
			                    $("#feat ul")
			                    .append("<li><img src='img/squaregray.gif' alt='' width='10' height='10' />&nbsp;<a id='"+this.ProductFeatureID+"' href='javascript:void(0);'>"+this.FeatureDescriptione+"</a></li>");
			               }
			               $('#'+pfid)
			                    .click(function() {
			                          //alert('clicked'+pfid);
			                          $("#content").width("700px");
                                            $("#prodright").show();
			                          $("#prodfeature ul").empty();
			                          $("#prodfeature ul")
			                          .append("<li>"+fctnt+"</li>");
			               
			                          })
			                if ((first)) {
			                        //alert('clicked first'+pfid);
			                        $("#content").width("700px");
                                          $("#prodright").show();
			                        $("#prodfeature ul").empty();
			                        $("#prodfeature ul")
			                        .append("<li>"+fctnt+"</li>");
			                        first=false;
			                        }
			                })
				}
  		});

   } // end of listfeatures

   function listeditions(prdid, test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductEditionsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductEditionsWebJson";
        }
   
      	$.ajax({type: "POST", async: false, contentType: "application/json; charset=utf-8",
                    url: locurl,
                    data: "{'ProdID': "+prdid+"}", dataType: "json",
                    success: function(edi) {
                                            
                       $("#editions ul").empty();
                       $(edi.d).each(function(){
                                 var peid = this.ProductEditionID;
                                 var pedesc = this.ProductEditionEn;
                                 var peplat = this.Platform;
                                 if (!(this.DisplayWeb == undefined)){
			                        $("#editions ul")
			                             .append("<li><img src='img/squaregray.gif' alt='' width='10' height='10' />&nbsp;<a id='"+this.ProductEditionID+"' href='javascript:void(0);'>"+this.ProductEditionEn+"</a></li>");

			                   }
			                                    
			                })
				}
			});

   } // end of listeditions
   
   Number.prototype.formatMoney = function(c, d, t){
        var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    };
   
   function paddnum(fnbr){
      
      while ((fnbr.length < 10))
      {
      	fnbr = '_' + fnbr;
      }
      //fnumber = '$' + fnumber;
      return fnbr;
   }

   function listprices(prdid, test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductPricesWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductPricesWebJson";
        }
   
       	$.ajax({type: "POST", async: false, contentType: "application/json; charset=utf-8",
                   url: locurl,
                   data: "{'ProdID': "+prdid+"}", dataType: "json",
                   success: function(ppric) {
                                            
                        $("#prices ul").empty();
                        $(ppric.d).each(function(){
                        var ppid = this.ProductPriceID;
                        var ppdesc = this.ProdDescEn;
                        var ppCAD = this.PriceCAD;
                        var ppisen = this.CodeISen;
                                if (!(this.PriceCAD == undefined)){
                                   var fpricecad = paddnum(parseFloat(this.PriceCAD).formatMoney(2, '.', ','));
                                   
                                    //alert(fpricecad);
			                        $("#prices ul")
			                        .append("<li><img src='img/squaregray.gif' alt='' width='10' height='10' />&nbsp;<a id='P"+this.ProductPriceID+"' href='javascript:void(0);'>"+this.ProdDescEn+"</a><br>"+this.CodeISen+":"+"<span>CAD$ "+fpricecad+"</span></li>");
			                        $('#P'+this.ProductPriceID)
                                    //.button()
			                        .click(function() {
			                            // confirm if want to add to product cart
			                            //alert(ppisen);
			                            //alert(ppCAD);
			                            if (parseFloat(ppCAD)>2000){
			                                alert('Note: we cannot sell this product on the web right now, please contact-us directly if you are ineterested in acquiring this product');
			                            }
			                            else {
			                                var answ = confirm('Do you wish to add this product to your shopping cart?');
			                                if (answ){
			                                alert('this will add the product '+ppisen+' to the shopping cart');
			                                }
			                            }
			                        });
			                  }
			         })
			}
		});

   } // end of listprices

   function AddFotowareItems(test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductsWebJson";
        }
   
		$.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'Categ':'FOTOWARE'}",
            dataType: "json",
            success: function(msg1) {
                 $(msg1.d).each(function(){
                        //alert(this);
                        //alert(msg1.d);
                        //alert(this.DisplayWeb);
                        if ((this.Active) && !(this.Active==undefined)){
                        var idp = this.ProductID;
                        var cd = this.FWProdCode;
                        var tx = this.ProductDescriptione;
                        $("#softfotoware ul")
                        .append("<li><img src='img/square.gif' alt='' width='10' height='10' /><a id='"+this.FWProdCode+"' href='javascript:void(0);'><span class='date'>"+this.FWProdCode+": </span>"+this.ProductDescriptione+"</a></li>");
                        $('#'+this.FWProdCode)
                            //.button()
			                .click(function() {
			                    // list corresponding product features
			                  listprodfeatures(idp, test);
				              listeditions(idp, test);
			                  listprices(idp, test);
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });


   } // end of AddFotowareItems
   function AddLaidBackItems(test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductsWebJson";
        }
   
		$.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'Categ':'LAIDBACK'}",
            dataType: "json",
            success: function(msg1) {
                 $(msg1.d).each(function(){
                        //alert(this);
                        //alert(msg1.d);
                        //alert(this.DisplayWeb);
                        if ((this.Active) && !(this.Active==undefined)){
                        var idp = this.ProductID;
                        var cd = this.FWProdCode;
                        var tx = this.ProductDescriptione;
                        $("#softlaidback ul")
                        .append("<li><img src='img/square.gif' alt='' width='10' height='10' /><a id='"+this.FWProdCode+"' href='javascript:void(0);'><span class='date'>"+this.FWProdCode+": </span>"+this.ProductDescriptione+"</a></li>");
                        $('#'+this.FWProdCode)
                            //.button()
			                .click(function() {
			                    // list corresponding product features
			                  listprodfeatures(idp, test);
				              listeditions(idp, test);
			                  listprices(idp, test);
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });


   } // end of AddLaidBackItems
   
   function AddColorScienceItems(test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductsWebJson";
        }
        
		$.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'Categ':'COLOUR SCIENCE'}",
            dataType: "json",
            success: function(msg1) {
                 $(msg1.d).each(function(){
                        //alert(this);
                        //alert(msg1.d);
                        //alert(this.DisplayWeb);
                        if ((this.Active) && !(this.Active==undefined)){
                        var idp = this.ProductID;
                        var cd = this.FWProdCode;
                        var tx = this.ProductDescriptione;
                        $("#softcolor ul")
                        .append("<li><img src='img/square.gif' alt='' width='10' height='10' /><a id='"+this.FWProdCode+"' href='javascript:void(0);'><span class='date'>"+this.FWProdCode+": </span>"+this.ProductDescriptione+"</a></li>");
                        $('#'+this.FWProdCode)
                            //.button()
			                .click(function() {
			                    // list corresponding product features
			                  listprodfeatures(idp, test);
				              listeditions(idp, test);
			                  listprices(idp, test);
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });


   } // end of AddColorScienceItems
   
   function AddPressITItems(test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductsWebJson";
        }
   
		$.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'Categ':'PRESSIT'}",
            dataType: "json",
            success: function(msg1) {
                 $(msg1.d).each(function(){
                        //alert(this);
                        //alert(msg1.d);
                        //alert(this.DisplayWeb);
                        if ((this.Active) && !(this.Active==undefined)){
                        var idp = this.ProductID;
                        var cd = this.FWProdCode;
                        var tx = this.ProductDescriptione;
                        $("#softpressit ul")
                        .append("<li><img src='img/square.gif' alt='' width='10' height='10' /><a id='"+this.FWProdCode+"' href='javascript:void(0);'><span class='date'>"+this.FWProdCode+": </span>"+this.ProductDescriptione+"</a></li>");
                        $('#'+this.FWProdCode)
                            //.button()
			                .click(function() {
			                    // list corresponding product features
			                  listprodfeatures(idp, test);
				              listeditions(idp, test);
			                  listprices(idp, test);
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });


   } // end of AddPressITItems

   function AddSimalisItems(test) {
   
        var locurl=""
        if (test){
        locurl="http://localhost/w/service.asmx/getProductsWebJson";
        } else {
        locurl="http://www.candam.com/fotoweb/cdmws/service.asmx/getProductsWebJson";
        }
   
		$.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurl,
            data: "{'Categ':'SIMALIS'}",
            dataType: "json",
            success: function(msg1) {
                 $(msg1.d).each(function(){
                        //alert(this);
                        //alert(msg1.d);
                        //alert(this.DisplayWeb);
                        if ((this.Active) && !(this.Active==undefined)){
                        var idp = this.ProductID;
                        var cd = this.FWProdCode;
                        var tx = this.ProductDescriptione;
                        $("#softsimalis ul")
                        .append("<li><img src='img/square.gif' alt='' width='10' height='10' /><a id='"+this.FWProdCode+"' href='javascript:void(0);'><span class='date'>"+this.FWProdCode+": </span>"+this.ProductDescriptione+"</a></li>");
                        $('#'+this.FWProdCode)
                            //.button()
			                .click(function() {
			                    // list corresponding product features
			                  listprodfeatures(idp, test);
				              listeditions(idp, test);
			                  listprices(idp, test);
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });


   } // end of AddSimalisItems

    function loadProductPageEn(test) { //**********************
    
        var p=getQueryVariable('p');
        //alert('p variable: '+p);
        
    
         $("#grp1").accordion({
            autoHeight: false,
            navigation: true,
            fillSpace: false,
            change: function(event, ui) { 
                if (ui.options.event=='click'){
                var selt = $( "#tabs" ).tabs("option", 'selected');
                    if (!(ui.options.active == selt)){
                    $( "#tabs" ).tabs( "select" , ui.options.active);
                       // alert("option:" + ui.options.active);
                    }
                }
            }

        });
        
        $("#grp2").accordion({
            autoHeight: false,
            navigation: true,
            fillSpace: false
        });
        $( "#tabs" ).tabs({
        select: function(event, ui) { 
            var selected = ui.index;
            $("#grp1").accordion( "activate" , selected )
            //alert("selected tab index: "+ui.index);
         }
        });

        
        switch (p)
        {
        	case 'FW':
        		$("#grp1").accordion( "activate" , 0 );
        		$( "#tabs" ).tabs( "select" , 0 );
        		break;
        	case 'LD':
        	    $("#grp1").accordion( "activate" , 1 );
        	    $( "#tabs" ).tabs( "select" , 1 );
        		break;
        	case 'CS':
        	    $("#grp1").accordion( "activate" , 2 );
        	    $( "#tabs" ).tabs( "select" , 2 );
        		break;
        	case 'PT':
        	    $("#grp1").accordion( "activate" , 3 );
        	    $( "#tabs" ).tabs( "select" , 3 );
        		break;
        	case 'DN':
        	    $("#grp1").accordion( "activate" , 4 );
        	    $( "#tabs" ).tabs( "select" , 4 );
        		break;
        }

	AddFotowareItems(test);
	AddLaidBackItems(test);
	AddColorScienceItems(test);
	AddPressITItems(test);
	AddSimalisItems(test);

    } // end of load product page english ************************
    
    function loadIndexPageEn(test) { //**********************
    
         $("#softaccor").accordion({
                autoHeight: false,
                navigation: true,
                fillSpace: false
            });
            
            $("#softtrywat").accordion({
                autoHeight: true,
                //collapsible: true,
                navigation: true,
                header: 'h3' 
            });
            
            var locurlnews=""
            var locurlprod=""
            if (!test){
            locurlnews="http://www.candam.com/fotoweb/cdmws/Service.asmx/getNewsWebJson";
            locurlprod="http://www.candam.com/fotoweb/cdmws/Service.asmx/getProductNewsAllJson";
            } else { //test=true
            locurlnews="http://localhost/w/Service.asmx/getNewsWebJson"
            locurlprod="http://localhost/w/Service.asmx/getProductNewsAllJson";
            }
            
            $.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurlnews,
            data: "{'Categ':'MINT'}",
            dataType: "json",
            success: function(jsonarray) {
                 $(jsonarray.d).each(function(){
                        //alert(this);
                        //alert(this.Headline);
                        //alert(this.NDate);
                        if (!(this.NDate == undefined)){
                        var dt = this.NDate;
                        var tx = this.paragraph;
                        $("#pressindex ul")
                        .prepend("<li><span class='date'>"+this.NDate+"</span><br/>"+this.Headline+"<button id='more"+this.ID+"' class='more'>+</button></li>");
                        $('#more'+this.ID)
                            .button()
			                .click(function() {
				                $('#dialogpress ul')
				                .empty();
				                $('#dialogpress ul')
				                .prepend("<li><span class='date'>"+dt+"</span><br/>"+tx+"</li>");
				                $('#dialogpress').dialog('open');
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });
            
            $.ajax({
            type: "POST",
            async: false, // cannot be async or would give results too late for components created then
            contentType: "application/json; charset=utf-8",
            url: locurlprod,
            data: "{}",  //no parameters
            dataType: "json",
            success: function(msg) {
                 $(msg.d).each(function(){
                        if (!(this.NDate == undefined)){
                        var dt = this.NDate;
                        var tx = this.paragraph;
                        $("#newsindex ul")
                        .prepend("<li><span class='date'>"+this.NDate+"</span><br/>"+this.Headline+"<button id='more"+this.ID+"' class='more'>+</button></li>");
                        $('#more'+this.ID)
                            .button()
			                .click(function() {
				                $('#dialogpress ul')
				                .empty();
				                $('#dialogpress ul')
				                .prepend("<li><span class='date'>"+dt+"</span><br/>"+tx+"</li>");
				                $('#dialogpress').dialog('open');
			                });
                        }
                  });
                         
            },
            error: function(err) {
            alert('Error:' + err.responseText + '  Status: ' + err.status); 
            }
            });
            
            $("#dialogpress").dialog({
			autoOpen: false,
			height: 330,
			width: 550,
			modal: true,
			buttons: {
				'OK': function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				//allFields.val('').removeClass('ui-state-error');
			}
		    });

    } // end of load index page english ************************
    
    function getQueryVariable(variable) { 
        var query = window.location.search.substring(1); 
        var vars = query.split("&"); 
        for (var i = 0; i < vars.length; i++) { 
            var pair = vars[i].split("="); 
            if (pair[0] == variable) { 
                return unescape(pair[1]); 
            } 
        } 
        //alert('Query Variable ' + variable + ' not found'); 
    } 


   /*$("document").ready(function(){

     

  });*/

// we cache everything, even javascript files.
// If we want to force a reload, we will add a generated timestamp or similar
// to the GET request parameters.
$.ajaxSetup({
    cache: true
});

// setting a global indicator which indicates if the site is currently busy or not.
var g_isLoading = false;
$(document).ajaxStart(function(){
    // adding the "loading" class to the body whenever an ajax request starts.
    $("body").addClass("loading");
    g_isLoading = true;
    showLoading();
});

$(document).ajaxStop(function(){
    // removing the loading class from the body if no ajax request is working anymore.
    $("body").removeClass("loading");
    g_isLoading = false;
    hideLoading();
});

// declaring global default values
var GLOBALS = {
    Search: "",
    Preview: false,
    PreviewAccess: false,
    PostBackUrl: "",
    KeywordMetaFieldId: 0
};

var CONFIG = {
    // the delay (in ms) which will occur after every selection
    // till the synchronizing process will be triggered
    // recommended: 1000-1500
    SelectionSyncDelay: 1250,
    // the size in pixels which will be used for the
    // hovering thumbnail preview
    // default: 450
    HoverPreviewSize: 450
}

/**
 * shows the loading indicator, will be called whenever a ajax request is running
 */
function showLoading(){
    

    $('.loadingIndicator .background').css("opacity", 0.2);
    $('.loadingIndicator').fadeIn(300);
}

/**
 * hides the loading indicator again
 */
function hideLoading(){
    
    window.setTimeout(function(){
        if(g_isLoading){
            return;
        }
        $('.loadingIndicator').fadeOut(300);
    }, 500);
}



