﻿
var object;
var url;
var PageType;
var Objparameters;
var MultipleTimeExecutionScript;
var OnceExecutionParameter = { 1: "Email", 3: "TotalGrossPrice" };

//=========================================================== Start Object Oriented Classes =====================================================//

//=============== Global Class which will be called on each page =====================//
var HeaderExit = false;


function GlobalFunction() {
    try {

        //Live
        Execute_ClientScript("cmSetClientID('90114925', 'true', 'ww5.buyagift.co.uk', 'buyagift.co.uk');");
                             

        //Test
       // Execute_ClientScript("cmSetClientID('60114925', 'false', 'testdata.coremetrics.com', 'buyagift.co.uk');");

        Execute_ClientScript("cmSetupOther({ 'cm_TrackImpressions': '' });");

    }
    catch (e) {
        DisplayError(e);
        HeaderExit = true;
    }
}


//=============== Category =====================//
try
{
    var Category;
    $(function () {

        Category = $.Class.create({
            initialize: function () { },

            //public property
            MultipleTimeExecutionScript: function () {
                return {};
            },

            //== Header Tags ===========
            Scriptfunctions: function () {

                var tags = {

                    //== Coremeterics =====
                    Client1: "cmCreatePageviewTag('PageId', 'CategoryId', null, null);",

                    //== Coremeterics scripts =====
                    Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
                }

                return tags;
            }
        });
    });

} catch (e) {}

//=============== Product =====================//

try 
{
var Product;
$(function () {

    Product = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== Header Tags ===========
        Scriptfunctions: function () {

            var tags = {


                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('PageId', 'CategoryId');",

                Client2: "cmCreateProductviewTag('ProductCode','ProductName','CategoryId');",

                Client3: "cmSetupOther({ 'cm_TrackImpressions': '' });"

            }

            return tags;
        }

      });
});


} catch (e) {}

//===============  Basket  =====================//

try 
{
var Basket;
$(function () {

    Basket = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return { 1: "cmCreateShopAction5Tag" };
        },

        //== Header Tags ===========
        Scriptfunctions: function () {

          /*  //<!-- Google Code for Basket Drop Out Remarketing List -->
            var GoogleScript = " <script type='text/javascript'>" +
                                " var google_conversion_id = 1071961716;" +
                                " var google_conversion_language = 'en';" +
                                " var google_conversion_format = '3';" +
                                " var google_conversion_color = '666666';" +
                                " var google_conversion_label = 'PcceCIiR7wEQ9KyT_wM';" +
                                " var google_conversion_value = 0;" +
                                " </script>   ";
                                " <script type='text/javascript' src='https://www.googleadservices.com/pagead/conversion.js'>" 
            GoogleScript = GoogleScript + " <noscript> <div style='display:inline;'>" +
                                            " <img height='1' width='1' style='border-style:none;' alt='' src='https://www.googleadservices.com/pagead/conversion/1071961716/?label=PcceCIiR7wEQ9KyT_wM&amp;guid=ON&amp;script=0'/>"+
            " </div> </noscript>";

            $('head').append(GoogleScript);            
            //<!--End Google Code for Basket Drop Out Remarketing List --> */
                  
            var tags = {
                  

                //== Coremetrics ShopAction5Tag
                Client1: "cmCreateShopAction5Tag('ProductCode','Title','Quantity','Price','CategoryId');",

                Client2: "cmDisplayShop5s();",                

                Client3: "cmCreatePageviewTag('Basket', 'Checkout', null);",

                Client4: "cmSetupOther({ 'cm_TrackImpressions': '' });"

           
        }
        return tags;
        }
    });
});

}catch (e) {}


//=============== Delivery Detail =====================//

try 
{
var DeliveryDetail;
$(function () {

    DeliveryDetail = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== Header Tags ===========
        Scriptfunctions: function () {
            
             //  <!-- Google Analytics start -->
            var FunnelScript =  "<script type='text/javascript'> " +
                                " var _gaq = _gaq || [];  _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                " _gaq.push(['_trackPageview', '/funnel_G1/DeliveryDetails.html']);" +
                                " (function() {" +
                                " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                " })();" +
                                " </script>";

            $('head').append(FunnelScript);            
            //<!-- Google Analytics end -->

            var tags = {

                //== Coremeterics =====                
                Client1: "cmCreatePageviewTag('DeliveryDetails', 'Checkout', null);",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }


            return tags;
        }       

    });
});

}
catch (e) {}


//=============== Billing Detail =====================//

try
{
var BillingDetail;
$(function () {

    BillingDetail = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== Header Tags ===========
        Scriptfunctions: function () {

            //<!-- Google Analytics start -->
            var FunnelScript =  "<script type='text/javascript'> " +
                                " var _gaq = _gaq || [];  _gaq.push(['_setAccount', 'UA-995853-4']); " +
                                " _gaq.push(['_trackPageview', '/funnel_G1/BillingDetails.html']); " +
                                " (function() { " +
                                " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                " })();" +
                                " </script>";

            $('head').append(FunnelScript);           
            //<!-- Google Analytics end -->

            var tags = {
                            
                //CoreMetrics Support 2 
                Client1: "cmCreatePageviewTag('BillingDetails', 'Checkout', null);",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }

    });
});

}
catch (e) {}


//=============== Payment Detail =====================//

try
{
    var PaymentDetail;
    $(function () {

        PaymentDetail = $.Class.create({
            initialize: function () { },

            //public property
            MultipleTimeExecutionScript: function () {
                return {};
            },

            //== Header Tags ===========
            Scriptfunctions: function () {
            
                 //<!-- Google Analytics start -->
                var FunnelScript =  "<script type='text/javascript'>" +
                                    " var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                    " _gaq.push(['_trackPageview', '/funnel_G1/PaymentDetails.html']);" +
                                    " (function() {" +
                                    " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                    " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                    " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                    " })();" +
                                    " </script>";

                $('head').append(FunnelScript);            
                //<!-- Google Analytics end -->

                var tags = {
                                   
                    //CoreMetrics Support 2 
                    Client1: "cmCreatePageviewTag('PaymentDetails', 'Checkout', null);",

                    Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
                }
                return tags;
            }
        });
    });

}
catch (e) {}

//=============== Order Confirmation =====================//
//     TotalGrossPrice = basket price including delivery charges.
//     OrderTotal = TotalAmount excluding delivery charges

try  
{
var Confirmation;
$(function () {

    Confirmation = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return { 1: "cmCreateShopAction9Tag", 2: "AwinProductReporting" };
        },

        Scriptfunctions: function () {

    
            /* This script has been moved to Confirmation.cshtml
  
            var OrderTotal = "OrderTotal";
            OrderTotal = SetParameters(OrderTotal);
            var SaleConversion = "<script language='JavaScript' type='text/javascript'>" +
            " var google_conversion_id = 1071961716;" +
            " var google_conversion_language = 'en';" +
            " var google_conversion_format = '1';" +
            " var google_conversion_color = 'ffffff';" +
            " var google_conversion_label = 'TGFkCJjiqgIQ9KyT_wM';" +
            " if (" + OrderTotal + ") { var google_conversion_value = " + OrderTotal + ";}" +
            " </script>" +
            " <script type='text/javascript' src='https://www.googleadservices.com/pagead/conversion.js'>" +
            " <noscript> <img height='1' width='1' border='0' src=https://www.googleadservices.com/pagead/conversion/1071961716/?value=" + OrderTotal + "&amp;label=TGFkCJjiqgIQ9KyT_wM&amp;guid=ON&amp;script=0/></noscript>"             
            $('head').append(SaleConversion);
            //<!-- End of Google Code for Sale Conversion Page -->
            */

//          <!--  Start Google Transactions code -->	
             var pageTracker_addTrans = SetParameters("pageTracker._addTrans('" + msOrderReference + "','bagstaging','OrderTotal','TotalBasketVat','DeliveryMethodGrossSellPrice','City','County','Country');");
            var pageTracker_addItem = Setparameters_AndReturnScript("pageTracker._addItem('" + msOrderReference + "','ProductCode','Title','CategoryName','Price','Quantity');")
            pageTracker_addItem = SetParameters(pageTracker_addItem);

            GoogleAnalytics = "<script type='text/javascript'>" +
                                    "   try { var pageTracker = _gat._getTracker('UA-995853-4');" +
                                    "   pageTracker._trackPageview();" +
                                        pageTracker_addTrans +
                                        pageTracker_addItem +
                                    "   pageTracker._trackTrans();" +
                                    "   } catch(err) {}</script>";

            $('head').append(GoogleAnalytics);
//          <!--  End Google Transactions code -->	

            /* <!-- Start  Shopzilla Script --> */
            var shopzilla = "<script language='javascript'>" +
            /* Performance Tracking Data */
                            " var mid   = '82754';" +
                            " var cust_type     = '1';" +
                            " var order_value   = '" + Objparameters.OrderTotal + "';" +
                            " var order_id      = '" + msOrderReference + "';" +
                            " var units_ordered = '" + Objparameters.ProductCount +"';" +
                            " </script>" +
                            " <script language='javascript' src='https://www.shopzilla.com/css/roi_tracker.js'></script>";
            $('head').append(shopzilla);
            /* <!-- End  Shopzilla Script --> */
            

            var tags = {

                Client1: "SetKenshooParameters('OrderTotal','" + msOrderReference + "', 'promocode', 'valueCurrency');",

                //==ShopAction5Tag
                Client2: "cmCreateShopAction9Tag('ProductCode', 'Title', 'Quantity','Price', 'Email', '" + msOrderReference + "' , 'OrderTotal', 'CategoryId');",

                //==COREMETRICS SUPPORT 2            
                Client3: "cmDisplayShop9s();",

                Client4: "cmCreateOrderTag('" + msOrderReference + "', 'TotalGrossPrice', 'Shipping', 'Email', 'City', 'County', 'PostCode');",
                                
                Client5: "AwinProductReporting('UnderlyingTypeId', 'ProductTypeId', 'AffiliateFlag', '" + msOrderReference + "', 'ProductCode', 'Title', 'Price', 'Quantity','CategoryName');",

                Client6: "SetAffiliateParameters('OrderTotal','" + msOrderReference + "','promocode',DeliveryMthodId, Deliverymethod, DelvieryPrice, ProductCode1, 'Title1', Price1, Quantity1);",

                Client7: "cmCreateRegistrationTag('Email','Email','City','County','PostCode','Country','');",

                Client8: "cmCreatePageviewTag('OrderConfirmation', 'Checkout', null);",

                Client9: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }

    });
});


} catch (e) {}


//=============== Account Order Confirmation =====================//
//     TotalGrossPrice = basket price including delivery charges.
//     OrderTotal = TotalAmount excluding delivery charges

try {
    var AccountOrderConfirmation;
    $(function () {

        AccountOrderConfirmation = $.Class.create({
            initialize: function () { },

            //public property
            MultipleTimeExecutionScript: function () {
                return { 1: "cmCreateShopAction9Tag", 2: "AwinProductReporting" };
            },

            Scriptfunctions: function () {



              /*  This script has been moved to Confirmation.cshtml
              
              //<!-- Google Code for Sale On New BaG Conversion Page -->            
                var OrderTotal = "OrderTotal";
                OrderTotal = SetParameters(OrderTotal);
                var SaleConversion = "<script language='JavaScript' type='text/javascript'>" +
                " var google_conversion_id = 1071961716;" +
                " var google_conversion_language = 'en';" +
                " var google_conversion_format = '1';" +
                " var google_conversion_color = 'ffffff';" +
                " var google_conversion_label = 'TGFkCJjiqgIQ9KyT_wM';" +
                " if (" + OrderTotal + ") { var google_conversion_value = " + OrderTotal + ";}" +
                " </script>" +
                " <script type='text/javascript' src='https://www.googleadservices.com/pagead/conversion.js'>" +
                " <noscript> <img height='1' width='1' border='0' src=https://www.googleadservices.com/pagead/conversion/1071961716/?value=" + OrderTotal + "&amp;label=TGFkCJjiqgIQ9KyT_wM&amp;guid=ON&amp;script=0/></noscript>"                 
                $('head').append(SaleConversion);
                //<!-- End of Google Code for Sale Conversion Page -->

            */
                //          <!--  Start Google Transactions code -->	
                var pageTracker_addTrans = SetParameters("pageTracker._addTrans('" + msOrderReference + "','bagstaging','OrderTotal','TotalBasketVat','DeliveryMethodGrossSellPrice','City','County','Country');");
                var pageTracker_addItem = Setparameters_AndReturnScript("pageTracker._addItem('" + msOrderReference + "','ProductCode','Title','CategoryName','Price','Quantity');")
                pageTracker_addItem = SetParameters(pageTracker_addItem);

                GoogleAnalytics = "<script type='text/javascript'>" +
                                    "   try { var pageTracker = _gat._getTracker('UA-995853-4');" +
                                    "   pageTracker._trackPageview();" +
                                        pageTracker_addTrans +
                                        pageTracker_addItem +
                                    "   pageTracker._trackTrans();" +
                                    "   } catch(err) {}</script>";

                $('head').append(GoogleAnalytics);
                //          <!--  End Google Transactions code -->	


                 /* <!-- Start  Shopzilla Script --> */
            var shopzilla = "<script language='javascript'>" +
            /* Performance Tracking Data */
                            " var mid   = '82754';" +
                            " var cust_type     = '0';" +
                            " var order_value   = '" + Objparameters.OrderTotal + "';" +
                            " var order_id      = '" + msOrderReference + "';" +
                            " var units_ordered = '" + Objparameters.ProductCount +"';" +
                            " </script>" +
                            " <script language='javascript' src='https://www.shopzilla.com/css/roi_tracker.js'></script>";
            $('head').append(shopzilla);

            /* <!-- End  Shopzilla Script --> */
            
                //<!-- Google Analytics start -->
                var FunnelScript = "<script type='text/javascript'>" +
                                " var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                " _gaq.push(['_trackPageview', '/funnel_G1/OrderConfirmation.html']);" +
                                " (function() {" +
                                " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                " })();" +
                                " </script>";


                $('head').append(FunnelScript);
                //<!-- Google Analytics end -->

                var tags = {

                    Client1: "SetKenshooParameters('OrderTotal','" + msOrderReference + "', 'promocode', 'valueCurrency');",

                    //==ShopAction5Tag
                    Client2: "cmCreateShopAction9Tag('ProductCode', 'Title', 'Quantity','Price', 'Email', '" + msOrderReference + "' , 'OrderTotal', 'CategoryId');",

                    //==COREMETRICS SUPPORT 2                                

                    Client3: "cmCreateOrderTag('" + msOrderReference + "', 'TotalGrossPrice', 'Shipping', 'Email', 'City', 'County', 'PostCode');",                                     
                    
                    Client4: "cmDisplayShop9s();",

                    Client5: "AwinProductReporting('UnderlyingTypeId', 'ProductTypeId', 'AffiliateFlag', '" + msOrderReference + "', 'ProductCode', 'Title', 'Price', 'Quantity','CategoryName');",

                    Client6: "SetAffiliateParameters('OrderTotal','" + msOrderReference + "','promocode',DeliveryMthodId, Deliverymethod, DelvieryPrice, ProductCode1, 'Title1', Price1, Quantity1);",

                    Client7: "cmCreateRegistrationTag('Email','Email','City','County','PostCode','Country','');",

                    Client8: "cmCreatePageviewTag('OrderConfirmation', 'AccountOrderConfirmation', null);",

                    Client9: "cmSetupOther({ 'cm_TrackImpressions': '' });"
                    
                }

                return tags;
            }

        });
    });


} catch (e) { }

//=============== Search =====================//

try 
{
var Searching;
$(function () {

    Searching = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var SearchKeyword = "SearchKeyword";
            SearchKeyword = SetParameters(SearchKeyword);
            //<!-- Google Analytics start -->
            var FunnelScript = "<script type='text/javascript'>" +
                                " var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                " _gaq.push(['_trackPageview', '/Search?Key=" + SearchKeyword + "']);" +
                                " (function() {" +
                                " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                " })();" +
                                " </script>";


            $('head').append(FunnelScript);
            //<!-- Google Analytics end -->


            var tags = {

                //== Coremeterics =====                

                Client1: "cmCreatePageviewTag('Search Results: PageId', 'CategoryId', 'SearchKeyword', 'NoOfResults');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"

               


            }

            return tags;
        }

    });
});

} catch (e) {}
//================================================ Start Checkout Classes ==============================//

//============= 1.	AccCheckout(Index) =================
try 
{
var AccCheckout;
$(function () {

    AccCheckout = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            //<!-- Google Analytics start -->
            var FunnelScript = "<script type='text/javascript'>" +
                                " var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                " _gaq.push(['_trackPageview', '/funnel_G1/AccountCheckout.html']);" +
                                " (function() {" +
                                " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                " })();" +
                                " </script>";

            $('head').append(FunnelScript);
            //<!-- Google Analytics end -->

            var tags = {

               
                
                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('AccountCheckout', 'Checkout');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }

    });
});


}
catch (e) {}

//============= 2.	AccCheckoutDeliveryAddressAdd(DeliveryAdd) =================

try
{
var AccCheckoutDeliveryAddressAdd;
$(function () {

    AccCheckoutDeliveryAddressAdd = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {

                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('AddDeliveryAddress', 'Checkout');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }

    });
});

}
catch (e) {}
//============= 3.	AccCheckoutDeliveryAddressEdit(DeliveryEdit) =================

try 
{
var AccCheckoutDeliveryAddressEdit;
$(function () {

    AccCheckoutDeliveryAddressEdit = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

       //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {

                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('EditDeliveryAddress', 'Checkout');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"

            }

            return tags;
        }

    });
});

}
catch (e) {}
//============= 4.	AccCheckoutBillingAddressEdit(BillingEdit) =================

var AccCheckoutBillingAddressEdit;
$(function () {

    AccCheckoutBillingAddressEdit = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {
                            
                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('EditBillingAddress', 'Checkout');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }
    });
});


//============= 5.	PayWithNewCard =================

var AccCheckoutPayWithNewCard;
$(function () {

    AccCheckoutPayWithNewCard = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {

                
                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('PayWithNewCard', 'Checkout');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }
    });
});

//====================================== Start Account Classes ==========================================//

var Account;
$(function () {

    Account = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {

                //== Coremeterics =====
                Client1: "cmCreatePageviewTag('Account', 'Account');",

                Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
            }

            return tags;
        }
    });
});


//====================================== Account With Registration ==========================================//

var AccountWithRegistration;
$(function () {

    AccountWithRegistration = $.Class.create({
        initialize: function () { },

        //public property
        MultipleTimeExecutionScript: function () {
            return {};
        },

        //== following functions will be executed on client side ===========
        Scriptfunctions: function () {

            var tags = {

                //== Coremeterics =====               

                Client1: "cmCreateRegistrationTag('Email','Email','City','County','PostCode','Country','');",

                Client2: "cmCreatePageviewTag('Account', 'Account');",

                Client3: "cmSetupOther({ 'cm_TrackImpressions': '' });"

            }

            return tags;
        }
    });
});

//=============== Paysecureley =====================//

try {
    var Securelogon;
    $(function () {

        Securelogon = $.Class.create({
            initialize: function () { },

            //public property
            MultipleTimeExecutionScript: function () {
                return {};
            },

            //== Header Tags ===========
            Scriptfunctions: function () {

                //<!-- Google Analytics start -->
                var FunnelScript = "<script type='text/javascript'>" +
                                    " var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-995853-4']);" +
                                    " _gaq.push(['_trackPageview', '/funnel_G1/Securelogon.html']);" +
                                    " (function() {" +
                                    " var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" +
                                    " ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" +
                                    " var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" +
                                    " })();" +
                                    " </script>";

                $('head').append(FunnelScript);
                //<!-- Google Analytics end -->

                var tags = {

                    
                    Client1: "cmCreatePageviewTag('Securelogon', 'Checkout', null);",

                    Client2: "cmSetupOther({ 'cm_TrackImpressions': '' });"
                }
                return tags;
            }
        });
    });

}
catch (e) { }



//This function is executed from Create new account view
function CreateAccountTag(CustomerId, Email, City, County, PostCode, Country) {

    Execute_ClientScript("cmCreateRegistrationTag('" + CustomerId + "','" + Email + "','" + City + "','" + County + "','" + PostCode + "','" + Country.options[Country.selectedIndex].value + "','');");

    Execute_ClientScript("cmCreatePageviewTag('Account', 'Account');");

    Execute_ClientScript("cmSetupOther({ 'cm_TrackImpressions': '' });");

}

function RegistrationTag() {

    Execute_ServerClientFunctions("cmCreateRegistrationTag('Email','Email','City','County','PostCode','Country','');", "Client");

    
}

//============================================================ End Object Oriented Classes =====================================================//





try {   
    GlobalFunction();

    //==Global object
//    var object_Global = new Global();
//    ExecuteFunctions(object_Global.Scriptfunctions());   
   
}
catch (e) {
    DisplayError(e);
    HeaderExit = true;
}

function PartialTagScript(_PageType) {

    //Parse Json object   
    var ctr = document.getElementById("hf_tagscript").value;
    Objparameters = jQuery.parseJSON(ctr);

    object = GetCurrentPartioalPageObject(_PageType);

    if (object == null) return true;

    //==function object creation
    var object_functions = object.Scriptfunctions();

    //==Calling Functions
    ExecuteFunctions(object_functions);
}

$(document).ready(function () {

    if (document.getElementById("hf_tagscript") == null || HeaderExit == true) return true;

    try {
        //Parse Json object   
        var ctr = document.getElementById("hf_tagscript").value;
        Objparameters = jQuery.parseJSON(ctr);


        //Get page type of current object    
        if (Objparameters["PageType"] == null) return true;
        PageType = Objparameters["PageType"];

        //If Customer has sign in from Securelogin       
        if (PageType == "AccCheckout" && Objparameters["login"] == true) 
            RegistrationTag();
        

        //Get Current Object
        object = GetCurrentPageObject(PageType);
        if (object == null) return true;

        //Get scripts whcih will be executed with product counts    
        MultipleTimeExecutionScript = object.MultipleTimeExecutionScript();

        //==functions object creation
        var object_functions = object.Scriptfunctions();
        ExecuteFunctions(object_functions);
        
    }
    catch (e) {
        DisplayError(e);
        return true;
    }
});


//== Iterate object and execute functions
function ExecuteFunctions(_object) {

    for (var key in _object) {
        
        if (CheckMultipleTimeExecutionScript(_object[key]) == true) {
            Setparameters_Execute(_object[key], key.replace(/\d+/g, ''));
        }
        else {
            Execute_ServerClientFunctions(_object[key], key.replace(/\d+/g, ''))
        }

    }
}


function CheckMultipleTimeExecutionScript(_script) {
    var returntype = false;

    for (key in MultipleTimeExecutionScript) {

        if (_script.indexOf(MultipleTimeExecutionScript[key]) == 0)
            returntype = true;
    }

    return returntype;
}

function OnceExecutionParameterTags(parameter) {
    var returntype = false;

    for (key in OnceExecutionParameter) {

        if (OnceExecutionParameter[key] == parameter)
            returntype = true;
    }

    return returntype;
}

//===== Execute Client side script =========
function Execute_ClientScript(_script) {   

//    if (window.execScript) {        // Internet Explorer and Google Chrome
//        execScript(_script, "JavaScript");
//    }
//    else {
//        if (window.eval) {
//            // the script language  is always JavaScript for the eval method
//            eval(_script);
//        }
//    }
    //alert(_script);
    _script = "<script type='text/javascript'>" + _script + " </script>";
    $('head').append(_script);

}

function Execute_ServerClientFunctions(_Script, _ScriptType) {

    //Set Parameters    
    _Script = SetParameters(_Script);      

    //
    Execute_ClientScript(_Script);        
    
}

//This will execute as number of time as products count and each time will replace parameters and execute Execute_ServerClientFunctions();
function Setparameters_Execute(_script, _scripttype) {

    var previousKey = "";
    var _counter = 1;
    var _script_modified;
    var firsttime = false;
   
    //Iterate with product count
    while (_counter <= Objparameters.ProductCount) {
        _script_modified = _script;

        //Iterate with parameters counts
        for (key in Objparameters) {

            //remove any numeric value
            var actualkey = key.replace(/\d+/g, '');

            //if it has completed its 1 product replacement round then exit for loop
            if (previousKey == actualkey)
                break;

            //replace with simple parameter with parameter number like productid to productid1
            if (OnceExecutionParameterTags(actualkey) == false)
                _script_modified = _script_modified.replace(actualkey, actualkey + _counter);


            if (firsttime == false) {
                previousKey = actualkey;
                firsttime = true;
            }

        }
        firsttime = false;
        previousKey = "";

        _counter = _counter + 1;     
        Execute_ServerClientFunctions(_script_modified, _scripttype);
    }

}

//This will execute as number of time as products count and each time will replace parameters and return all scripts
function Setparameters_AndReturnScript(_script) {

    var previousKey = "";
    var _counter = 1;
    var _script_modified;
    var firsttime = false;
    var TotalScript="";

    //Iterate with product count
    while (_counter <= Objparameters.ProductCount) {
        _script_modified = _script;

        //Iterate with parameters counts
        for (key in Objparameters) {

            //remove any numeric value
            var actualkey = key.replace(/\d+/g, '');

            //if it has completed its 1 product replacement round then exit for loop
            if (previousKey == actualkey)
                break;

            //replace with simple parameter with parameter number like productid to productid1
            if (OnceExecutionParameterTags(actualkey) == false)
                _script_modified = _script_modified.replace(actualkey, actualkey + _counter);


            if (firsttime == false) {
                previousKey = actualkey;
                firsttime = true;
            }

        }
        firsttime = false;
        previousKey = "";

        _counter = _counter + 1;
        TotalScript = TotalScript + _script_modified;
    }

    return TotalScript;
}

//Get array of all target scripts of current page
function GetCurrentPageObject(PageType) {
    var urls = new Array();
    var obj;

    switch (PageType) {

        case "Product":
            obj = new Product();
            break;

        case "Category":
            obj = new Category();
            break;

        case "Basket":
            obj = new Basket();
            break;

        case "Confirmation":
            obj = new Confirmation();
            break;

        case "DeliveryDetail":
            obj = new DeliveryDetail();
            break;

        case "BillingDetail":
            obj = new BillingDetail();
            break;

        case "PaymentDetail":
            obj = new PaymentDetail();
            break;

        case "AccCheckout":
            obj = new AccCheckout();
            break;

        case "AccCheckoutDeliveryAddressAdd":
            obj = new AccCheckoutDeliveryAddressAdd();
            break;

        case "AccCheckoutDeliveryAddressEdit":
            obj = new AccCheckoutDeliveryAddressEdit();
            break;

        case "AccCheckoutBillingAddressEdit":
            obj = new AccCheckoutBillingAddressEdit();
            break;

        case "Search":
            obj = new Searching();
            break;

        case "AccountWithRegistration":
            obj = new AccountWithRegistration();
            break;

        case "AccountOrderConfirmation":
            obj = new AccountOrderConfirmation();
            break;

        case "Account":
            obj = new Account();
            break;

        case "AccCheckoutPayWithNewCard":
            obj = new AccCheckoutPayWithNewCard();
            break;


        default:
            obj = null;
    }

    return obj;
}


//Get array of all target scripts of current page
function GetCurrentPartioalPageObject(PageType) {
    var urls = new Array();
    var obj;

    switch (PageType) {              

        case "AccCheckoutDeliveryAddressAdd":
            obj = new AccCheckoutDeliveryAddressAdd();
            break;

        case "AccCheckoutDeliveryAddressEdit":
            obj = new AccCheckoutDeliveryAddressEdit();
            break;

        case "AccCheckoutBillingAddressEdit":
            obj = new AccCheckoutBillingAddressEdit();
            break;
            
        case "Account":
            obj = new Account();
            break;

        case "AccountWithRegistration":
            obj = new AccountWithRegistration();
            break;

        case "Securelogon":
            obj = new Securelogon();
            break;

        default:
            obj = null;
    }

    return obj;
}


// Set parameters from Json Object to Script
function SetParameters(script) {
var keyfound = true;
var wordsCounter = script.split(',');
wordsCounter = wordsCounter.length;

    for (var key in Objparameters) {
        
        while (keyfound == true) {
            if (script.indexOf(key) > -1 & wordsCounter > 0) {
                script = script.replace(key, Objparameters[key]);
                wordsCounter = wordsCounter - 1;
            }
            else
                keyfound = false;
        }

        keyfound = true;
    }
    return script;
}

function DisplayError(ex) {
    //alert(ex);
    return true;

}


//value = version
// key = browser name
function GetBrowserName() {
    $.each($.browser, function (key, value) {
        return key;
    });
}

